Tutorial :problem in showing all files of a directory



Question:

hey guys im looking for a way to show all mp3 files in a directory

this is my code to get that :

    if ($handle = opendir($dirPath)) {           while (false !== ($file = readdir($handle))) {             if ($file = ".mp3" && $file = "..") {               echo '               <track>                <location>'.$dirPath.$file.'</location>                <creator>'.$file.'</creator>              </track>              ';                  }         }     closedir($handle);  }  

now i know that this script will only show mp3 files in parent directory , but i need to show all mp3 files in all directory inside parent directory

problem is this code cant show files inside sub directories !


Solution:1

That code won't work at all. As you are setting the $file variable to ".." the result will be a lot of xml containing $dirPath and "..".

This is what you are looking for :)

$it = new RecursiveDirectoryIterator('path/to/files/');  foreach (new RecursiveIteratorIterator($it) as $file)  {      echo $file->getPathname() . '<br />';  }  


Solution:2

You'll have to make a recursive function to search for all the MP3s.

Also, you probably meant if ($file == ".mp3" && $file == "..") { instead of if ($file = ".mp3" && $file = "..") {, and after that's changed, you get a condition that's always false. What are you trying to do there?


Solution:3

like icktoofay said, you'll have to make a recursive function. also, your code has an error:

if ($file = ".mp3" && $file = "..") {  

won't work (and if ($file == ".mp3" && $file == "..") { is wrong, too). that line should look like this:

if (substr($file,-4) == ".mp3" || $file == "..") {  

if you want to show the ".." - else it's just like this:

if (substr($file,-4) == ".mp3") {  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »