0

我正在尝试使用当前目录的内容填充 HTML 表单的下拉列表。我尝试使用 PHP 的 scandir() 函数将这些文件作为数组输出,然后将它们输入到 HTML 表单中的选项值标记中。

我查看了 SO 和外部可用的各种解决方案,但似乎没有一个对我有用。

这就是我的代码现在的样子:

<form action="" >
        <input type="submit" class="Links" value="Select Input">
        <select >               
            <?php 
                $dir="./inputfiles/"; 
                $filenames = scandir($dir); 
                foreach($filenames as $file){
                    echo '<option value="' . $filenames . '">' . $filenames . '</option>';
                    }
            ?>                      
        </select> 
</form> 

现在我在下拉菜单中绝对没有选项。

我对 PHP 非常陌生,非常感谢您对如何进行这项工作的反馈。


进一步的变化:

我尝试了下面给出的解决方案,但似乎都没有。我更改了代码以检查 PHP 脚本是否能够在 html 表单列表中输出任何变量。

<form action="" >
        <input type="submit" class="Links" value="Select Input">
        <select >               
            <?php 
                  $someval = "Video";
                  echo '<option value="value"> ' . $someval .' </option>';
            ?>                      
        </select> 
</form>

它显示 ' 。$一些。而不是菜单栏中的视频

4

3 回答 3

2

你必须$file在 echo out not中使用$filenames。像这样:

echo '<option value="' . $file . '">' . $file . '</option>';

有关更多信息,请参阅PHPforeach

于 2012-12-14T00:16:01.787 回答
2

遍历数组时,您需要使用$file连接,而不是$filenames

echo '<option value="' . $file . '">' . $file . '</option>';

如果inputfiles存在于同一目录中,则应使用路径:inputfiles/

于 2012-12-14T00:16:21.600 回答
1

您的脚本有几个问题。

首先,您需要在选项中输出正确的变量:

echo '<option value="' . $file . '">' . $file . '</option>';

其次,您可能需要在循环中添加检测...因为您可能不想输出它们。您可能还想排除目录。

第三,您可能应该明确您要扫描的目录。尝试使用完整的文件路径。如果您需要它相对于当前执行文件的目录,您可以执行以下操作:

$dir= __DIR__ . DIRECTORY_SEPARATOR . 'inputfiles'; // no need for trailing slash

Fourth, you might want to consider working with something like DirectoryIterator to give you some more convenient methods to do what you are looking to do (i.e. verifying it's an actual file before listing it). So something like this:

$dir= __DIR__ . DIRECTORY_SEPARATOR . 'inputfiles';
$iterator = new DirectoryIterator($dir);
foreach ($iterator as $fileinfo) {
    if($fileinfo->isFile()) {
        echo '<option value="' . $fileinfo->getFilename() . '">' . $fileinfo->getFilename() . '</option>';
    }
}

In this trivial example, it you won't necessarily gain a lot (in terms of saving extra code) by using DirectoryIterator, but I certainly like to point out it's usage when I can, because if you needed to start doing things like showing file size, file permissions, file modification times, etc. It is much easier to do it using the DirectoryIterator class (or RecursiveDirectoryIterator class if you need to recursive) than using traditional PHP's file system functions.

于 2012-12-14T00:31:08.177 回答