Creating a dynamic Navigation-Menu using PHP and XML

In this tutorial I will be showing you how to create a website navigation menu using PHP and XML

first create the XML file


<page url=”index.php?id=Home”>Home</page>
<page url=”index.php?id=about”>About</page>
<page url=”index.php?id=Events”>Events</page>
<page url=”index.php?id=Contact”>Contact</page>


Create a php file to that will load our XML file using simplexml_load_file()


$title =$_GET[‘id’]; //page id

$xml = simplexml_load_file(“menu.xml”); //load the xml file using simplexml

print ‘<ul id=”nav”>’;// Menu unordered list opening tag
foreach($xml->link as $link){//For each link node read it as $link

print “<li”;//List opening tag
print ‘ class=”‘;//List class to show the current page as class=”current_page”
if($title == $link->page){ //If the $title is the same as the page that is being viewed then set class to current page
print ‘current_page ‘;

print $link->page.'”‘;//This is the default class of every link, meaning if the page is Home then its class is Home as well

‘><a href=”‘.$link
is where attribute url is used to link to the pages

print “</li>”;//List Closing tag

print “</ul>”;//Menu unordered list closing tag

From here you can use css to style your menu

The output should be as follows

<ul id=”nav”>
<li class=”Home current_page“>Home</li> <!–if current page isHome –>
<li class=”About”>About</li>
<li class=”Events”>Events</li>
<li class=”Contact”>Contact</li>

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s