views:

59

answers:

6

Hi folks,

I have a directory: Audio/ and in that will be mp3 files only. I'm wanting to automate the process of creating links to those files. Is there a way to read a directory and add filenames within that directory to an array?

It'd be doubly cool if we could do an associative array, and have the key be the file name minus the .mp3 tag.

Any ideas?

To elaborate: I actual have several Audio/ folders and each folder contains mp3s of a different event. The event details are being pulled from a database and populating a table. That's why I'm duplicating code, because right now in each Audio/ folder, I'm having to define the filenames for the download links and define the filenames for the mp3 player.

Thank you! This will greatly simplify my code as right now I'm repeating tons of code over and over!

+1  A: 

Yes: use scandir(). If you just want the name of the file without the extension, use basename() on each element in the array you received from scandir().

Mark Trapp
Sweet! Trying it out now!
Joel
+1  A: 

This should be able to do what you're looking for:

// Read files
$files = scandir($dirName);
// Filter out non-files ('.' or '..')
$files = array_filter($files, 'is_file');
// Create associative array ('filename' => 'filename.mp3')
$files = array_combine(array_map('basename', $files), $files);
awgy
+1  A: 

Sure...I think this should work...

$files[] = array();
$dir = opendir("/path/to/Audio") or die("Unable to open folder");
    while ($file = readdir($dir)) {
        $cleanfile = basename($file);
        $files[$cleanfile] = $file;
    }
    closedir($dir);

I imagine that should work...

Rafael
+3  A: 

The SPL way is with DirectoryIterator:

$files = array();
foreach (new DirectoryIterator('/path/to/files/') as $fileInfo) {
    if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
    $files[] = $fileInfo->getFilename();
}
Brenton Alker
I like this way even better! You missed the $ on files[]
Joel
So I did. Fixed.
Brenton Alker
A: 
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
  if ($file != "." && $file != "..") {
    $results[] = $file;
  }
}
closedir($handler);

this should work, if you want any files to be excluded from the array, just add them to the if statement, same for file extensions

Raz
+1  A: 

And for completeness : you could use glob as well :

$files = array_filter(glob('/path/to/files/*'), 'is_file'); 

This will return all files (but not the folders), you can adapt it as needed.

To get just the filenames (instead of files with complete path), just add :

$files = array_map('basename', $files);
wimvds