why do we get parent elements when we call the method simplexmlelementxpath for a child element?

In XPath, when you use //, you are saying a node in any position relative to the current node. With XPath this also includes nodes higher in the document as well as enclosed in this element.

There are several ways to solve it in this particular scenario…

With reference to What’s the difference between //node and /descendant::node in xpath?, you can use the descendant axis…

foreach ($nodeList as $node) {

which only uses nodes inside the base node (in this case $node).

Or if the hierarchy in your document is exactly as you have in your document, a simpler way is to use SimpleXML object notation (with a loop to show each one)…

foreach ($nodeList as $node) {
    // For each enclosed tag
    foreach ( $node->tag as $tag )  {
        // Echo the v attribute
        echo $tag['v'].PHP_EOL;

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top