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条)

报告相同问题?

悬赏问题

  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?