开发者

PHP: Directory Navigation Menu

I have a question that I haven't been able to find the answer/script to. I'm just learning to use PHP. I'm using Perch as a CMS and has been going great so far.

I've run into a snag when it comes to adding new pages. Something that I want PHP to do is be able to create a dynamic navigation menu for only that directory.

For example, I have three pages in my 'about' directory.

root /about /index.php - page2.php - page3.php

I want to be able to output a side navigation menu based off only that directory.

Home - Page2 - Page3

And when the client/user creates a new page, it'll automatically add it to the list. So...

root /about /index.php - page2.php - page3.php - newPage.php

..开发者_运维问答.creates...

Home - Page2 - Page3 - New Page

Can anyone point me into a direction of a script or help me get started?

Thanks!


There are quite a few php functions to iterate through directories. I think the cleanest is using PHP SPL (Standard PHP Library)'s Directory Iterator.

http://www.php.net/manual/en/class.directoryiterator.php

$dir = new DirectoryIterator('about');
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        // Can make the link here
        echo $fileinfo->getFilename();
    }
}

The advantage is you have a lot of class functions available to you.

If you need more than the filename you can use:

  • getPathname()
  • getPath()
  • getBasename()
  • isDir()

And so on... see the docs for all the possibilities.


foreach (glob('*.php') as $filename) {
    echo $filename; //Make menu item here
}

However, you should probably not create a menu based on your filesystem. I suggest you use a template engine, like Smarty.


Sure can. I use this method to find all files in a directory and add the file's name and extension into an array. Through the magic of a while loop, I can do something for each file.

$files = scandir('directory/of/files/');

This creates a new array named $files. You can use a while or for each loop. I use for each in this case, since it's the easiest.

foreach ($files as $value)
{
  $file = explode('.',$value); // Explode splits a variable by whatever

Now that you have the files and the actual name of the files, you can add them to your navigation. I would add the filename to a variable.

  $navigation .= $file['0']; // Adds the file's name to the navigation variable
}

You can wrap the $file['0'] in a <span> or <li> and add appropriate styling for your navigation. I recommend searching Google for some fancy navigation examples. I use unordered lists and just style them with CSS.

Play around with the foreach loop and styling to get the perfect navigation ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜