Home > Article > Backend Development > How to use PHP and CGI to implement website navigation and menus
How to use PHP and CGI to implement website navigation and menus
Navigation and menus are a very important part of website design. They can provide navigation guidance for the overall structure and main functions of the website. In this article, we will learn how to use PHP and CGI (Common Gateway Interface) to implement website navigation and menus.
To implement the navigation and menu of the website, first we need to create a data structure containing navigation and menu items. Usually, this data structure can be represented by an array, where each element represents a navigation or menu item and contains the name and corresponding URL address.
The sample code is as follows:
$menu = array( array('name' => '首页', 'url' => 'index.html'), array('name' => '产品', 'url' => 'products.html'), array('name' => '关于我们', 'url' => 'about.html'), array('name' => '联系我们', 'url' => 'contact.html') );
Next, we need to use PHP and CGI to dynamically generate the navigation and menu of the website. We can use a loop to iterate through the navigation and menu items in the array and output them as HTML links.
The sample code is as follows:
echo '<ul>'; foreach ($menu as $item) { echo '<li><a href="' . $item['url'] . '">' . $item['name'] . '</a></li>'; } echo '</ul>';
The above code will generate an unordered list (ul) containing links for each menu item. After running the code, the output HTML code is similar to:
<ul> <li><a href="index.html">首页</a></li> <li><a href="products.html">产品</a></li> <li><a href="about.html">关于我们</a></li> <li><a href="contact.html">联系我们</a></li> </ul>
By inserting the above code into the location of the website's navigation and menu, we can dynamically generate the website's navigation and menu.
In addition to statically generating navigation and menus, we can also add special styles to the corresponding navigation or menu items to mark them based on the URL address of the current page.
The sample code is as follows:
$currentURL = $_SERVER['REQUEST_URI']; echo '<ul>'; foreach ($menu as $item) { $class = ($item['url'] == $currentURL) ? 'active' : ''; echo '<li class="' . $class . '"><a href="' . $item['url'] . '">' . $item['name'] . '</a></li>'; } echo '</ul>';
The above code compares the URL address of the current page with the URL address of the menu item. If they are equal, a CSS class named "active" is added for tagging. The current navigation or menu item. You can customize the style of this CSS class as needed.
The above is the detailed content of How to use PHP and CGI to implement website navigation and menus. For more information, please follow other related articles on the PHP Chinese website!