How do i implement a dynamic navigation in php?
e.g
Home | about | contact | faq | tutorials
i need to automatically generate the links dynamically
It seems that you want to include a menu file in all your pages. You can use include().
In all your pages:
<html>
<body>
<?php include('navigation.php'); ?>
Contents of this page here...
</body>
</html>
And in navigation.php:
<div id="mainmenu">
<a href="home.php">Home</a> | <a href="about.php">About</a> | etc...
</div>
This way you can update your navigation menu just once for all your pages.
i agree with the first solution even if its a bit simply. For me you have to split your website into some script where you include your navigation script like the second solution.
but if you really want to make a dynamic navigation, your data cant be write in a file and they are stock in a database or on an xml file.... to do that you have to create a class or a function who parse your data and create array like first solution.
/* header.php (main header template)*/
<html>
<head>
...
</head>
<body>
<div id="mainMenu">
<?php echo Navigation::getNav($databaseCnx);?>
</div>
and in another script you have to create a class who manage the data
<?php
class Navigation{
static function getNav($cnx){
$menuList = '<ul>';
$dataFromDataBase = $cnx->getArray('MySqlRequest');
foreach($dataFromDataBase as $menu) {
$menuList .='<li><a href="'.$menu->uri.'">'.$menu->name.'</a></li>';
}
$menuList .= '</ul>';
return $menuList;
}
}
i write it fast but i hope i can help some who look for tips to create dynamic menu.
If you just want to display a menu for a known set of pages without re-architecting your current code, how about this:
<?php
$pages = array(
'index.php' => 'Home',
'about.php' => 'About',
'contact.php' => 'Contact',
'faq.php' => 'FAQ',
'tutorials.php' => 'Tutorials',
) ;
$currentPage = basename($_SERVER['REQUEST_URI']) ;
?>
<div id="menu">
<ul id="menuList">
<?php foreach ($pages as $filename => $pageTitle) {
if ($filename == $currentPage) { ?>
<li class="current"><?php echo $pageTitle ; ?></li>
<?php } else { ?>
<li><a href="<?php echo $filename ; ?>"><?php echo $pageTitle ; ?></a></li>
<?php
} //if
} //foreach
?>
</ul>
</div>
Put this in its own file, say menu.php
, and then include it in each page. Then you can style your menu with CSS.