【问题标题】:Make a menu with the names of the files in a directory [duplicate]使用目录中文件的名称制作菜单[重复]
【发布时间】:2013-10-20 13:57:22
【问题描述】:

我想为我的网站制作一个额外的小菜单。是否可以获取目录中文件的名称并将它们放在菜单中。

所以如果你有一个包含文件的目录:facebook.php;推特.php; stackoverflow.html;你会得到一个这样的菜单:

  • 脸书
  • 推特
  • 堆栈溢出

如果可能的话,我想选择他得到什么样的文件。所以我希望他得到 .php 和 .html 文件的名称,而不是 .css 文件的名称。

有人可以帮我解决这个问题吗?

【问题讨论】:

标签: php html menu directory


【解决方案1】:

试试scandir()方法

在循环中使用 is_dir() 检查当前文件是否为目录。然后你可以用 [dirname]/[dirname.php] 获取路径。检查是否存在文件,然后您可以显示链接。

$files = scandir('menus');
$links = array();
foreach ($files as $file) {
   if ($file == "." || $file == "..")
      continue;

   if (is_dir($file)) {
      $menuFile = "./menus/$file/$file.php";
      if (is_file($menuFile)) {
         $links[$file] = $menuFile;
      }
   }
}

//display the links

【讨论】:

    【解决方案2】:

    我喜欢 glob():

    foreach(glob("$dir/{*.php,*.html}", GLOB_BRACE) as $file) {
        //whatever
    }
    

    $files = glob("$dir/{*.php,*.html}", GLOB_BRACE); //then use $files wherever
    

    您可以使用带有 PATHINFO_BASENAME 的 pathinfo() 来仅获取文件名 PATHINFO_FILENAME 以获取它而无需扩展名。

    【讨论】:

    • 现在我知道如何获取文件名了,但你也知道如何将每个文件名放在另一个 li 中吗?我对php不是很擅长,但我想学习它。
    • @Moreno__R:在第一个示例中,只需将 //whatever 替换为 echo "<li>".pathinfo($file, PATHINFO_FILENAME)."</li>";
    猜你喜欢
    • 2020-10-30
    • 2014-09-11
    • 2022-09-30
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 2019-01-23
    相关资源
    最近更新 更多