I am implementing a PHP syntax parser from an XML file. I am doing relatively well. However, I need the parser to be more dynamic. I need to implement a recursive function that will continue the loop for each found child node. A node can contain many child_nodes in another child_node. What I have done so far has been to implement a separate foreach loop with different variable names for each child_node, however this is not acceptable as it is not so flexible.
This is my xml file:
<sitemap>
<node>
<id>rootnode</id>
<link>home.html</link>
</node>
<node>
<id>about</id>
<link>about.html</link>
</node>
<node>
<id>contact</id>
<link>contact.html</link>
<child_node>
<id>contact_uk</id>
<link>contact_uk.html</link>
<child_node>
<id>customer_support_uk</id>
<link>customer_support_uk.html</link>
</child_node>
</child_node>
<child_node>
<id>contact_usa</id>
<link>contact_usa.html</link>
</child_node>
</node>
<node>
<id>products</id>
<link>products.html</link>
</node>
</sitemap>
You may notice that the node contact has a child_id in child_node. Here I need a recursive function.
This is my current PHP code:
$source = 'sitemap.xml';
$sitemap = simplexml_load_file($source, null, true);
foreach ($sitemap->node as $node) {
if ($node->child_node != "") {
echo "$node->link<br/>";
foreach ($node->child_node as $child) {
if ($child->child_node != "") {
echo " " . $child->link . "<br/>";
foreach ($child->child_node as $innerchild) {
echo " " . $innerchild->link . "<br/>";
}
} else {
echo " " . $child->link . "<br/>";
}
}
} else {
echo "$node->link<br/>";
}
}
PHP , foreach _ child_node. - , PHP-, child_node child_node, ?
!