之前php代码遍历文件和文件夹代码,之前用的是比较常见的代码
单个函数遍历文件夹

glob和scandir
遍历文件夹和文件PHP代码

  1. function my_scandir($dir)
  2. {
  3. $files = array();
  4. if ( $handle = opendir($dir) ) {
  5. while ( ($file = readdir($handle)) !== false )
  6. {
  7. if ( $file != ".." && $file != "." ) {
  8. if ( is_dir($dir . "/" . $file) ) {
  9. $files[$file] = my_scandir($dir . "/" . $file);
  10. }  else {
  11. $files[] = $file;
  12. }
  13. }
  14. }
  15. closedir($handle);
  16. return $files;
  17. }
  18. }

上面的代码在文件很多的时候就会有问题,没有办法正常执行,
快速高效遍历文件和文件夹方法
遍历文件

  1. $dir = new DirectoryIterator(dirname(__FILE__));
  2. foreach ($dir as $fileinfo) {
  3. echo $fileinfo->getFilename() . "\n";
  4. }

遍历文件夹和文件

  1. function test($path = './'){
  2. $file = new FilesystemIterator($path);
  3. foreach ($file as $fileinfo) {
  4. echo $fileinfo->getFilename() . "</br>";
  5. if($fileinfo->isDir()){
  6. test($path . $fileinfo->getFilename() . '/');
  7. }
  8. }
  9. }
相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!