Is there an easy way to read file names in a directory and add to an array?

I have a directory: Audio/and it will only contain mp3 files. I want to automate the process of creating links to these files. Is there any way to read the directory and add the file names in this directory to the array?

It would be doubly cool if we could make an associative array and have a key in the file name minus the .mp3 tag.

Any ideas?

To develop: I have several folders Audio/, and each folder contains mp3 files of another event. Information about the event is retrieved from the database and populated with a table. That's why I duplicate the code, because right now in each folder Audio/I need to determine the file names for the download links and determine the file names for the mp3 player.

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

+3
source share
6 answers

SPL path with DirectoryIterator :

$files = array();
foreach (new DirectoryIterator('/path/to/files/') as $fileInfo) {
    if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
    $files[] = $fileInfo->getFilename();
}
+3
source

And for completeness: you can use glob :

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

This will return all files (but not folders), you can adapt them if necessary.

To get only file names (instead of files with a full path), simply add:

$files = array_map('basename', $files);
+3
source

: scandir(). , basename() , scandir().

+1

, :

// 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);
+1

... , ...

$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 suppose this should work ...

+1
source
$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, the same goes for file extensions

+1
source

Source: https://habr.com/ru/post/1760240/


All Articles