Search code examples
phpxmlsimplexml

simplexml_load_file() - generate html menu out of xml


I'm trying to create a menu for a php-website out of a xml file. The XML-Structure is:

<?xml version="1.0" encoding="utf-8" ?>
<MenuRoot>
    <Menu id="home" text="Startseite" url="../overview.php"></Menu>
    <Menu id="system" text="System" url="../system.php">
        <SubMenu id="system_sub1" text="Allgemein" url="../tba.php"></SubMenu>
        <SubMenu id="system_sub2" text="Abmelden" url="../logout.php"></SubMenu>
    </Menu>
</MenuRoot>

My PHP Code looks like - this does not work:

if(file_exists('/var/www/content/menu.xml')) {
$xml = simplexml_load_file('/var/www/content/menu.xml');
    foreach($xml->children() as $menu) {
        echo '<li><a href="'.$menu->Menu['url'].'">'.$menu->Menu['text'].'</a>';
        if(NULL !== $menu->children()):
            echo '<ul>';
            foreach($menu->children() as $submenu) {
                echo '<li><a href="'.$submenu->SubMenu['url'].'">'.$submenu->SubMenu['text'].'</a></li>';
            }
            echo '</ul>';
        endif;
        echo '</li>';
    }
}
else:
    write_log(sprintf("menu.xml not found"));
endif;

I tried some different methods and did the basic way like, which works:

if(file_exists('/var/www/content/menu.xml')) {
$xml = simplexml_load_file('/var/www/content/menu.xml');
echo '<li><a href="'.$xml->Menu[0]['url'].'">'.$xml->Menu[0]['text']..'</a>';
}

what am I doing wrong with my loops and accessing variables in my not working example?

thanks!


Solution

  • When you access $menu->Menu['url'], $menu is already the Menu node, and should be $menu['url'].

    You can access to your menu directly using $xml->Menu. Then you can use count() to check the number of children:

    $xml = simplexml_load_file('/var/www/content/menu.xml');
    foreach($xml->Menu as $menu) {
        echo '<li><a href="'.$menu['url'].'">'.$menu['text'].'</a>';
    
        if (count($menu->SubMenu)) {
    
            echo '<ul>';
            foreach($menu->SubMenu as $submenu) {
                echo '<li><a href="'.$submenu['url'].'">'.$submenu['text'].'</a></li>';
            }
            echo '</ul>';
    
        }
        echo '</li>';
    }
    

    Outputs:

    <li>
        <a href="../overview.php">Startseite</a>
    </li>
    <li>
        <a href="../system.php">System</a>
        <ul>
            <li><a href="../tba.php">Allgemein</a></li>
            <li><a href="../logout.php">Abmelden</a></li>
        </ul>
    </li>