PHP目录中特定文件的列表

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)

  • @Jessica这个答案似乎比选择的更好.改变它怎么样? (26认同)

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查看扩展的简单方法

  • 这回答了原始问题,但我认为问题应该是"是否有明确的PHP语法可以为您做到这一点?".答案是肯定的,正如你从最高投票的答案看到的那样. (4认同)

Art*_*cto 10

$it = new RegexIterator(new DirectoryIterator("."), "/\\.xml\$/i"));

foreach ($it as $filename) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用迭代器的递归变体遍历整个目录层次结构.

  • 在PHP> = 5.3中,您还可以使用GlobIterator:http://de3.php.net/manual/en/class.globiterator.php (4认同)

小智 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)