如何在php中列出所有文件夹及其文件


How to list all the folders and its files in php

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

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

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

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

如何从目录迭代程序循环中排除文件类型

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

希望它能帮助