我已经设置了一个基本脚本,它发布了一组路径以在其中查找模板文件;目前它只搜索两层深度,我在理解一个广泛的循环以迭代所有子目录直到长度为 0 的逻辑时遇到了一些麻烦。
所以如果我有这样的结构:
./components
./components/template.html
./components/template2.html
./components/side/template.html
./components/side/template2.html
./components/side/second/template.html
./components/side/second/template2.html
./components/side/second/third/template.html
./components/side/second/third/template2.html
理想情况下,当我希望它检查所有子目录和传递的目录中的 .html 文件时,它只会在“side”目录中搜索 .html 文件。到目前为止,这是我的工作代码:
<?php
function getFiles($path){
$dh = opendir($path);
foreach(glob($path.'/*.html') as $filename){
$files[] = $filename;
}
if (isset($files)) {
return $files;
}
}
foreach ($_POST as $path) {
foreach (glob($path . '/*' , GLOB_ONLYDIR) as $secondLevel) {
$files[] = getFiles($secondLevel);
}
$files[] = getFiles($path);
}
sort($files);
print_r(json_encode($files));
?>
最佳答案
PHP 内置了适合您的完美解决方案。
示例
// Construct the iterator
$it = new RecursiveDirectoryIterator("/components");
// Loop through files
foreach(new RecursiveIteratorIterator($it) as $file) {
if ($file->getExtension() == 'html') {
echo $file;
}
}
资源
关于php - 如何递归遍历PHP中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25909820/