目录中特定文件的PHP列表

以下代码将列出目录中的所有文件


<?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>

尽管这是非常简单的代码,但可以完成工作。


我现在正在寻找一种仅列出结尾处带有.xml(或.XML)的文件的方法,该怎么办?


30秒到达战场
浏览 474回答 3
3回答

阿晨1998

if ($handle = opendir('.')) {&nbsp; &nbsp; while (false !== ($file = readdir($handle)))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'xml')&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; closedir($handle);}使用substr和strrpos查看扩展的简单方法

海绵宝宝撒

您将要使用 glob()例:$files = glob('/path/to/dir/*.xml');

大话西游666

$it = new RegexIterator(new DirectoryIterator("."), "/\\.xml\$/i"));foreach ($it as $filename) {&nbsp; &nbsp; //...}您还可以使用迭代器的递归变体遍历整个目录层次结构。
打开App,查看更多内容
随时随地看视频慕课网APP