Parsing an XML navigation sitemap with PHP -


i implementing php sitemap parser xml file. doing relatively well. however, need parser more dynamic. need implement recursive function continue looping every child_node found. node can contain many child_nodes within child_node. did till implement seperate foreach loop different variable names every child_node not acceptable not flexible.

this 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 can note node contact has child_node within child_node. need recursive function.

this current php code:

    $source = 'sitemap.xml';       // load file     $sitemap = simplexml_load_file($source, null, true);       foreach ($sitemap->node $node) {          if ($node->child_node != "") {             echo "$node->link<br/>";             foreach ($node->child_node $child) {                 if ($child->child_node != "") {                     echo "&nbsp;&nbsp;" . $child->link . "<br/>";                     foreach ($child->child_node $innerchild) {                         echo "&nbsp;&nbsp;&nbsp;&nbsp;" . $innerchild->link . "<br/>";                     }                 } else {                     echo "&nbsp;&nbsp;" . $child->link . "<br/>";                 }             }         } else {             echo "$node->link<br/>";         }     } 

this php has correct output have create seperate foreach loop every child_node within parent child_node. can point me in right direction on how change php code in order traverse every child_node within child_node found in sitemap?

many thanks!

not tested...but should work:

function print_node($node, $level){  echo str_repeat("-",$level);  echo "$node->link\n";  if ($node->child_node != "") {        foreach ($node->child_node $child) {           print_node($child,$level+1);        }   }  } $source = 'sitemap.xml';   $sitemap = simplexml_load_file($source, null, true); foreach ($sitemap->node $node)     print_node($node,0); 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -