I’m having difficulty using parentNode with DomXpath.
<?php
$html = <<<STR
<div id="bar">
<p>item1</p>
<ul>
<li class="foo">item2</li>
<li>item3</li>
<li>item4</li>
</ul>
</div>
STR;
$doc = new DOMDocument;
$doc->loadHTML( $html );
$xpath = new DomXpath($doc);
$nodeFoo = $xpath->query("//*[@id='bar']//*[@class='foo']");
echo $nodeFoo->item(0)->nodeValue;
$nodeClimb = $nodeFoo->parentNode; // causes an error
echo $nodeClimb.nodeName;
?>
I expected that the last line yields ‘ul’ which is the parent node name of the retrieved node, $nodeFoo. What am I doing wrong?
Firstly, you have a typo on your last line:
echo $nodeClimb.nodeName;should beecho $nodeClimb->nodeName;However, your main problem is something that you’ve spotted on one line but not on the next: the XPath query returns not a single
DOMNode, but an instance ofDOMNodeListcontaining all the matches for that query.So just as you have selected the first item in the list to echo (
echo $nodeFoo->item(0)->nodeValue;), you need to select an item to assign as the parent ($nodeClimb = $nodeFoo->item(0)->parentNode;).