简体   繁体   中英

List MP3 Files In An Array From Directories & Sub-directories In PHP

I Want To Get List Of Files In My Directories & Sub-Directories In An Array In PHP Language .

I Have 2 Type Of Code :

1- First Code:
This Bellow Code List All Files In An Array , But There Are Folders And Sub-directories In Array :

$files = dir_scan('pathAddress'); 
function dir_scan($folder) {
$files = glob($folder);
foreach ($files as $f) {
    if (is_dir($f)) {
        $files = array_merge($files, dir_scan($f .'/*')); // scan subfolder
    }
}
return $files;
}
echo "<pre>";
print_r($files);
echo "</pre>";

Result Of Top Code : Click For View Image

2- Second Code:
This Bellow Code List All MP3 Files But In String Not Array! & I Can't Convert It To Array.

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

Result Of Top Code : Click For View Image

Finally, I Want An Array Of MP3 Files In All Directories & Sub-Directories Specified Location .

Thanks For Your Help

This code might help you, It will check all the folders and in return, will get file names ..

<?php 

function listFolderFiles($dir)
{    
    $file_names = array();
    foreach (new DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {



            if ($fileInfo->isDir()) {


                // checking directory empty or not, if not then append list     
                $isDirEmpty = !(new \FilesystemIterator($fileInfo->getPathname()))->valid();

                if($isDirEmpty != 1)
                {

                    $file_names[] = listFolderFiles($fileInfo->getPathname());
                }



            }
            else 
            {
                $file_names[] = $fileInfo->getPathname() ;  
            }
        }
    }


    // Splicing Array 
        for ($i=0; $i<count($file_names); $i++) {

            if (is_array($file_names[$i])) {
                    array_splice($file_names, $i, 1, $file_names[$i]);
            }
        }


    return $file_names;
}


$res = listFolderFiles('main_folder_name');
echo '<pre>';
print_r($res);


?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM