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

M.E*_*M.E 46 php directory loops

我需要在子目录中的所有文件中创建一个循环.你可以帮我构建我的代码,如下所示:

$main = "MainDirectory";
loop through sub-directories {
    loop through filels in each sub-directory {
        do something with each file
    }
};
Run Code Online (Sandbox Code Playgroud)

你能帮忙吗,PLZ?

Mic*_*cki 141

RecursiveDirectoryIterator与RecursiveIteratorIterator结合使用.

$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
Run Code Online (Sandbox Code Playgroud)

  • 如果它对任何人都有用,上面的`$ file`是[SplFileInfo](http://php.net/manual/en/class.splfileinfo.php)的一个实例,其中包含的方法与(getBasename,getSize等) - 花了我一点时间才弄明白. (6认同)
  • @NickF 是的,很高兴知道!`$file-&gt;isDir`、`$file-&gt;isDot` 也非常有用。 (3认同)

GSt*_*Sto 10

如果你的子目录有子目录,你可能想要使用递归函数

$main = "MainDirectory";

function readDirs($main){
  $dirHandle = opendir($main);
  while($file = readdir($dirHandle)){
    if(is_dir($main . $file) && $file != '.' && $file != '..'){
       readDirs($file);
    }
    else{
      //do stuff
    }
  } 
}
Run Code Online (Sandbox Code Playgroud)

没有测试代码,但这应该接近你想要的.

  • 它将陷入无限循环,试图以递归方式读取目录"." (单点 - 当前目录).你需要修改你的if语句:if(is_dir($ file)和$ file!='.') (3认同)
  • 缺少右括号`while($ file = readdir($ dirHandle){`,否则效果很好!谢谢. (2认同)

小智 7

您需要添加递归调用的路径.

function readDirs($path){
  $dirHandle = opendir($path);
  while($item = readdir($dirHandle)) {
    $newPath = $path."/".$item;
    if(is_dir($newPath) && $item != '.' && $item != '..') {
       echo "Found Folder $newPath<br>";
       readDirs($newPath);
    }
    else{
      echo '&nbsp;&nbsp;Found File or .-dir '.$item.'<br>';
    }
  }
}

$path =  "/";
echo "$path<br>";

readDirs($path);
Run Code Online (Sandbox Code Playgroud)


Fed*_*TIK 5

我喜欢glob它的通配符:

foreach (glob("*/*.txt") as $filename) {
    echo "$filename\n";
}
Run Code Online (Sandbox Code Playgroud)

细节和更复杂的场景.

但是如果你有一个复杂的文件夹结构RecursiveDirectoryIterator肯定是解决方案.