【问题标题】:How to list all the folders and its files in php [duplicate]如何在php中列出所有文件夹及其文件[重复]
【发布时间】:2013-12-29 05:54:47
【问题描述】:

我有一个文件夹,其中包含目录。一些目录包含文件,另一些包含另一个目录及其文件。我想要列出文件夹中的所有文件。假设我的文件夹是 A,它包含文件夹 B 和 CB 包含一些 mp3 文件,在 C 中有另一个文件夹 D,在 D 中有一些 mp3 文件。如何列出 B 和 D 中的所有 mp3 文件。请帮助。

【问题讨论】:

  • 你尝试了吗?从dir()开始
  • 查找glob()RecursiveDirectoryIterator

标签: php file sorting directory scandir


【解决方案1】:
 function Read_Dir($dir) {
        $dh = opendir($dir);
        $files = array();
        while (($file = readdir($dh)) !== false) {
            $flag = false;
            if ($file !== '.' && $file !== '..') {
                  // check here if file is a directory then use it recursively
                $files[] = trim($file);

            }
        }
        return $files;

    }

希望对你有帮助

【讨论】:

    【解决方案2】:

    在扫描目录时,您只需要 mp3 文件。尝试目录迭代器

    $scan_it = new RecursiveDirectoryIterator("/example_dir");
    
    foreach(new RecursiveIteratorIterator($scan_it) as $file) {
      if (strtolower(substr($file, -4)) == ".mp3") {
        echo $file;
      }
    }
    

    How to exclude file types from Directory Iterator loop

    【讨论】:

      【解决方案3】:
      function find_all_files($dir) 
      { 
          $root = scandir($dir); 
          foreach($root as $value) 
          { 
              if($value === '.' || $value === '..') {continue;} 
              if(is_file("$dir/$value")) {$result[]="$dir/$value";continue;} 
              foreach(find_all_files("$dir/$value") as $value) 
              { 
                  $result[]=$value; 
              } 
          } 
          return $result; 
      } 
      

      【讨论】:

      • 你应该包括你的代码源的链接:ch2.php.net/scandir
      • 不。我很久以前在我的代码中使用过它。忘记从哪里复制了。
      • 听起来不错。也检查链接。
      • 很高兴你检查了。终于找到源码了:)
      • 非常感谢。效果很好
      猜你喜欢
      • 1970-01-01
      • 2012-07-21
      • 2017-01-15
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2019-06-19
      • 2021-10-18
      • 2018-06-08
      相关资源
      最近更新 更多