dougou8458 2012-07-23 19:18
浏览 88
已采纳

如何使用PHP将目录中的文件名作为选项填充到下拉菜单?

I'm trying to create a drop down menu that points to a directory and populates a drop down menu with the names of certain files in that directory using PHP.

Here's what I'm working with:

<?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>
";
    }
}  

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

echo "$select";
?> 

This bit of code is giving me an errors, and I'm not even really attached to it if there's a better way of trying to accomplish what I'm trying to do.

  • 写回答

3条回答 默认 最新

  • dst8922 2012-07-23 19:25
    关注

    It would be easier to use glob() because it can handle wildcards.

    // 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>
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料