tags:

views:

2527

answers:

4

I'm translating my C# code for YouTube video comments into PHP. In order to properly nest comment replies I need to re-arrange XML nodes. In PHP I'm using DOMDocument and DOMXPath which closely corresponds to C# XmlDocument. I've gotten pretty far in my translation but now I'm stuck on getting the parent node of a DOMElement. A DOMElement does not have a parent_node() property, only a DOMNode provides that property.

After determining that a comment is a reply to a previous comment based in the string "in-reply-to" in a link element, I need to get its parent node in order to nest it beneath the comment it is in reply to:

// Get the parent entry node of this link element
$importnode = $objReplyXML->importNode($link->parent_node(), true);
A: 

That may sound stupid, but why don't you try to get a DOMNode object in the first place and use the DOMNode property? How do you end up with a DOMElement object?

Vincent
+5  A: 

DOMElement is a subclass of DOMNode, so it does have parent_node property. Just use $domNode->parentNode; to find the parent node.

In your example, the parent node of $importnode is null, because it has been imported into the document, and therefore does not have a parent yet. You need to attach it to another element before it has a parent.

Marius
A: 

Because I need to test the DOMElement object for the "in-reply-to" string in one of its attribute values. Blame Google for making their XML structure so difficult to work with. Now I think I just need the current DOMNode in the DOMNodeList and then I can get its parent??

$links = $domXPath->query('//tns:entry//tns:link');
// $links is a DOMNodeList. $link is a DomElement.
foreach ($links as $link) {
foreach ($link->attributes as $attrName => $attrNode) {
 if (ereg("in-reply-to", $attrNode->nodeValue)) 
 {
  $intReplyCount = $intReplyCount + 1;
  echo $link->attributes->getNamedItem("href")->nodeValue . "\n";
  // STEP 1 - copy this reply node to a XmlDocument
  $objReplyXML->load('empty.xml');
  $temp = $objReplyXML->getElementsByTagName('feed')->item(0);
  // Get the parent entry node of this link element
  $importnode = $objReplyXML->importNode($links->parent_node(), true);
  $temp->appendChild($importnode);

    }
A: 

I'm not entirely sure how your code works, but it seems like you have a small error in your code. On the line you posted in your question you have $link->parent_node(), but in the answer with the entire code snippet you have $link**s**->parent_node(). I don't think the s should be there. Also, I think you should use $link->parentNode, not $link->parent_node().

Marius