Search code examples
phpxmlsimplexml

How to recursively walk tree with SimpleXMLIterator?


I have this sample code, why my code can find only test3 tag? Where are test and test2?

$iter = new RecursiveIteratorIterator(
    new SimpleXMLIterator(file_get_contents('./test.xml'))
);

foreach ($iter as $node) {
    echo "Tag found: ".$node->getName()."\n";
}

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<test>
  <test2>
    <test3>dsfds</test3>
  </test2>
</test>

Solution

  • When using RecursiveIteratorIterator, the default mode is JUST to list the leaves(http://php.net/manual/en/recursiveiteratoriterator.construct.php). If you change the construction to

    $iter = new RecursiveIteratorIterator(
            new SimpleXMLIterator($xml)
            , RecursiveIteratorIterator::SELF_FIRST);
    

    This indicates to also list the various other parts of the structure and will output...

    Tag found: test2
    Tag found: test3