我已经建立了一个基本脚本,该脚本发布了一系列路径以在其中查找模板文件;目前,它仅在两个级别进行深层搜索,我遇到了一些麻烦,无法在逻辑上进行广泛的循环,以迭代所有子目录,直到长度为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文件,而我希望它检查所有子目录和传递的目录中的.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/