如何使用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.

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

以下是我正在使用的内容: p>

 &lt;?php 
 
  $ path =“pages /”;  //如果脚本位于您想要的文件的另一个目录中,则更改此项
 $ show = array('。php','。html');  //要显示的文件类型
 
 $ select =“&lt; select name = \”content \“id = \”content \“&gt;”; 
 
 $ dh = @opendir($ path);  
 
而(假!==($ file = readdir($ dh))){
 $ ext = substr($ file,-4,4); 
 if(in_array($ ext,$ show))  {
 $ select。=“&lt; option value ='$ path / $ file'&gt; $ file&lt; / option&gt; 
”; 
} 
} 
 
 $ select。=“&lt; / 选择&gt;“; 
closedir($ dh); 
 
echo”$ select“; 
?&gt;  
  code>  pre> 
 
 

这段代码给了我一个错误,如果有更好的方法来尝试完成我的工作,我甚至都不会真正依赖它 试图做。 p> div>

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

You need a full path reference (i.e. /var/www/pages/) instead of just "pages".

Also you might consider using DirectoryIterator object for easily getting to directroy information (if you are using PHP 5).

I don't know, which errors you get. But I think it won't work with the $show array because you're comparing the last 4 chars of the file with the contents of the array. Instead of $ext=substr($file,-4,4); you could write $ext=substr($file, strrpos( $file, ".")); which gives you the string from the position of the last occurance of ".".

Also I suggest for test reason that you omit the @ opening the directory because I think that the path cannot be found.