PHP读取子目录并遍历文件如何?

我需要创建一个遍历子目录中所有文件的循环。您能帮我构造我的代码吗?


$main = "MainDirectory";

loop through sub-directories {

    loop through filels in each sub-directory {

        do something with each file

    }

};


慕雪6442864
浏览 429回答 3
3回答

料青山看我应如是

将RecursiveDirectoryIterator与RecursiveIteratorIterator结合使用。$di = new RecursiveDirectoryIterator('path/to/directory');foreach (new RecursiveIteratorIterator($di) as $filename => $file) {&nbsp; &nbsp; echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';}

牛魔王的故事

如果您的子目录包含子子目录,则可能需要为此使用递归函数$main = "MainDirectory";function readDirs($main){&nbsp; $dirHandle = opendir($main);&nbsp; while($file = readdir($dirHandle)){&nbsp; &nbsp; if(is_dir($main . $file) && $file != '.' && $file != '..'){&nbsp; &nbsp; &nbsp; &nbsp;readDirs($file);&nbsp; &nbsp; }&nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; //do stuff&nbsp; &nbsp; }&nbsp; }&nbsp;}没有测试代码,但这应该接近您想要的。

收到一只叮咚

您需要将路径添加到递归调用中。function readDirs($path){&nbsp; $dirHandle = opendir($path);&nbsp; while($item = readdir($dirHandle)) {&nbsp; &nbsp; $newPath = $path."/".$item;&nbsp; &nbsp; if(is_dir($newPath) && $item != '.' && $item != '..') {&nbsp; &nbsp; &nbsp; &nbsp;echo "Found Folder $newPath<br>";&nbsp; &nbsp; &nbsp; &nbsp;readDirs($newPath);&nbsp; &nbsp; }&nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; echo '&nbsp;&nbsp;Found File or .-dir '.$item.'<br>';&nbsp; &nbsp; }&nbsp; }}$path =&nbsp; "/";echo "$path<br>";readDirs($path);
打开App,查看更多内容
随时随地看视频慕课网APP