【问题标题】:How to populate a drop down menu with file names from a directory as options using PHP?如何使用 PHP 将目录中的文件名作为选项填充下拉菜单?
【发布时间】:2012-07-22 01:43:45
【问题描述】:

我正在尝试创建一个下拉菜单,该菜单指向一个目录,并使用 PHP 使用该目录中某些文件的名称填充下拉菜单。

这是我正在使用的:

<?php

$path = "pages/"; //change this if the script is in a different dir that the files you want
$show = array( '.php', '.html' ); //Type of files to show

$select = "<select name=\"content\" id=\"content\">";

$dh = @opendir( $path );

while( false !== ( $file = readdir( $dh ) ) ){
    $ext=substr($file,-4,4);
        if(in_array( $ext, $show )){       
            $select .= "<option value='$path/$file'>$file</option>\n";
    }
}  

$select .= "</select>";
closedir( $dh );

echo "$select";
?> 

这段代码给了我一个错误,如果有更好的方法来尝试完成我正在尝试做的事情,我什至不会真正依恋它。

【问题讨论】:

  • readdir(): 提供的参数不是在线 ... 中的有效目录资源 ...

标签: php html file drop-down-menu directory


【解决方案1】:

使用glob() 会更容易,因为它可以处理通配符。

// match all files that have either .html or .php extension
$file_matcher = realpath(dirname(__FILE__)) . '/../pages/*.{php,html}';

foreach( glob($file_matcher, GLOB_BRACE) as $file ) {
  $file_name = basename($file);
  $select .= "<option value='$file'>$file_name</option>\n";
}

【讨论】:

  • 这给了我一个下拉菜单,但填充的是 php 脚本目录中的文件,而不是我想要的目录。
  • @antiquarichat $path 设置为什么?
  • 我在url.com/admin...中有php脚本...我希望它指向url.com/pages...这基本上就是我设置的。 $path = "url.com/pages";
  • @antiquarichat 看看我的更新,看看是否能解决问题
  • 越来越近,它指向正确的目录...包括文件名在内的整个路径作为每个选项的值给出。我只需要显示文件名。
【解决方案2】:

我不知道,你得到了哪些错误。但我认为它不适用于 $show 数组,因为您将文件的最后 4 个字符与数组的内容进行比较。而不是$ext=substr($file,-4,4);,你可以写$ext=substr($file, strrpos( $file, "."));,它会从最后一次出现“.”的位置为你提供字符串。

另外,出于测试原因,我建议您省略打开目录的@,因为我认为找不到路径。

【讨论】:

    【解决方案3】:

    您需要完整的路径引用(即 /var/www/pages/),而不仅仅是“页面”。

    您也可以考虑使用 DirectoryIterator 对象来轻松获取目录信息(如果您使用的是 PHP 5)。

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      相关资源
      最近更新 更多