php函数文件操作指南:如何递归遍历目录?
PHP 函数文件操作指南:如何递归遍历目录?
在 PHP 中,我们可以使用[RecursiveDirectoryIterator](https://www.php.net/manual/en/class.recursivedirectoryiterator.php)来递归遍历目录。
语法
$rii = new RecursiveDirectoryIterator($dir);$files = new RecursiveIteratorIterator($rii);foreach ($files as $file) { // 对每个文件执行操作}
其中:
实战案例
以下是一个递归遍历目录并显示文件名的示例:
$dir = 'path/to/directory';$rii = new RecursiveDirectoryIterator($dir);$files = new RecursiveIteratorIterator($rii);foreach ($files as $file) { echo $file->getPathname() . "";}
输出:
立即学习“PHP免费学习笔记(深入)”;
path/to/directory/file1.txtpath/to/directory/file2.txtpath/to/directory/subdirectory1/file3.txtpath/to/directory/subdirectory1/file4.txtpath/to/directory/subdirectory2/file5.txt
注意
在使用RecursiveDirectoryIterator时,需要注意以下几点: