Parsing XML Navigation Syntax Using PHP

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';


    // load as file
    $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 "&nbsp;&nbsp;" . $child->link . "<br/>";
                    foreach ($child->child_node as $innerchild) {
                        echo "&nbsp;&nbsp;&nbsp;&nbsp;" . $innerchild->link . "<br/>";
                    }
                } else {
                    echo "&nbsp;&nbsp;" . $child->link . "<br/>";
                }
            }
        } else {
            echo "$node->link<br/>";
        }
    }

PHP , foreach _ child_node. - , PHP-, child_node child_node, ?

!

+3
2

... :

function print_node($node, $level){
 echo str_repeat("-",$level);
 echo "$node->link\n";
 if ($node->child_node != "") {
       foreach ($node->child_node as $child) {
          print_node($child,$level+1);
       }
  }

}
$source = 'sitemap.xml';


$sitemap = simplexml_load_file($source, null, true);
foreach ($sitemap->node as $node)
    print_node($node,0);
+4

node.

function processChildren( $node )
{
    foreach( $node->child_node as $child )
    {
        echo "$child->link<br/>";
        if( count( $child->child_node ) )
        {
            processChildren( $child );
        }
    }
}

, .; -)

+1

Source: https://habr.com/ru/post/1793081/


All Articles