如何递归地遍历PHP中的文件? [英] How to recursively iterate through files in PHP?

查看:36
本文介绍了如何递归地遍历PHP中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个基本脚本,该脚本发布了一系列路径以在其中查找模板文件;目前它只搜索两层深,我在理解一个广泛循环的逻辑时遇到了一些麻烦,以迭代所有子目录,直到长度为 0.

I have set up a basic script that is posting an array of paths to find template files inside them; currently it's only searching two levels deep and I'm having some troubles getting my head around the logic for an extensive loop to iterate all child directories until the length is 0.

所以,如果我有这样的结构:

So if I have a structure like this:

./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文件.到目前为止,这是我的工作代码:

It's only searching up to the "side" directory for .html files when ideally I want it to check all child directories and the passed directory for .html files. Here is my working code so far:

<?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为您内置了完美的解决方案.

PHP has the perfect solution for you built in.

// Construct the iterator
$it = new RecursiveDirectoryIterator("/components");

// Loop through files
foreach(new RecursiveIteratorIterator($it) as $file) {
    if ($file->getExtension() == 'html') {
        echo $file;
    }
}

资源

  • DirectoryIterator-手册
  • 这篇关于如何递归地遍历PHP中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆