Jes*_*ica 46 php directory file list
以下代码将列出目录中的所有文件
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if (($file != ".")
&& ($file != ".."))
{
$thelist .= '<LI><a href="'.$file.'">'.$file.'</a>';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<UL>
<P><?=$thelist?></p>
</UL>
Run Code Online (Sandbox Code Playgroud)
虽然这是非常简单的代码,但它完成了这项工作.
我现在正在寻找一种方法来列出最后只有.xml(或.XML)的文件,我该怎么做?
Dav*_*ell 193
你会想要使用 glob()
例:
$files = glob('/path/to/dir/*.xml');
Run Code Online (Sandbox Code Playgroud)
Bob*_*mer 48
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'xml')
{
$thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';
}
}
closedir($handle);
}
Run Code Online (Sandbox Code Playgroud)
使用substr和strrpos查看扩展的简单方法
Art*_*cto 10
$it = new RegexIterator(new DirectoryIterator("."), "/\\.xml\$/i"));
foreach ($it as $filename) {
//...
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用迭代器的递归变体遍历整个目录层次结构.
小智 5
我使用这个代码:
<?php
{
//foreach (glob("images/*.jpg") as $large)
foreach (glob("*.xml") as $filename) {
//echo "$filename\n";
//echo str_replace("","","$filename\n");
echo str_replace("","","<a href='$filename'>$filename</a>\n");
}
}
?>
Run Code Online (Sandbox Code Playgroud)