为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕雪6442864 2019-12-26 09:38:09
我需要创建一个遍历子目录中所有文件的循环。您能帮我构造我的代码吗?$main = "MainDirectory";loop through sub-directories {    loop through filels in each sub-directory {        do something with each file    }};
查看完整描述

3 回答

?
料青山看我应如是

TA贡献1772条经验 获得超7个赞

将RecursiveDirectoryIterator与RecursiveIteratorIterator结合使用。


$di = new RecursiveDirectoryIterator('path/to/directory');

foreach (new RecursiveIteratorIterator($di) as $filename => $file) {

    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';

}


查看完整回答
反对 回复 2019-12-26
?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

如果您的子目录包含子子目录,则可能需要为此使用递归函数


$main = "MainDirectory";


function readDirs($main){

  $dirHandle = opendir($main);

  while($file = readdir($dirHandle)){

    if(is_dir($main . $file) && $file != '.' && $file != '..'){

       readDirs($file);

    }

    else{

      //do stuff

    }

  } 

}

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


查看完整回答
反对 回复 2019-12-26
?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

您需要将路径添加到递归调用中。


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);


查看完整回答
反对 回复 2019-12-26
  • 3 回答
  • 0 关注
  • 428 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信