Traversing a Tree of XML Nodes Using Recursion
<?php
$doc = new DomDocument("1.0");
$doc->loadXML( file_get_contents("data.xml") );
$root = $doc->firstChild;
traverse( $root );
function traverse( DomNode $node, $level=0 ){
handle_node( $node, $level );
if ( $node->hasChildNodes() ) {
$children = $node->childNodes;
foreach( $children as $kid ) {
if ( $kid->nodeType == XML_ELEMENT_NODE ) {
traverse( $kid, $level+1 );
}
}
}
}
function handle_node( DomNode $node, $level ) {
for ( $x=0; $x<$level; $x++ ) {
print " ";
}
if ( $node->nodeType == XML_ELEMENT_NODE ) {
print $node->tagName."<br />\n";
}
}
?>
Related examples in the same category