Jump to content

Best way to list files in a directory by extension


guyfromfl

Recommended Posts

I have a script that works perfectly, for one type of file extension.

 

What I want to do now is be able to list all files in a set of file types.

 

I want to pass the argument to the fileSystem class's loadFiles method like this:

 

$some_var = $fileSystem->loadFiles(DATA_DIRECTORY, "csv,xls,etc");

 

Then in the loadFiles method it reads the dir for each file, then test its extension.  If they are of the right type, then push it on the returned array.

 

Now I am having problems testing if the file's extension is in the array.  If I use

 

if (strpos(getExt($file),  $array_of_wanted_exts))...

 

php would match php3..

 

Does anybody have a better method?

class RecursiveFileExtensionFilterIterator extends RecursiveFilterIterator
{
    private $validFileExtensions = array();
    
    public function __construct($recursiveIterator, $validFileExtensions) {
        $this->validFileExtensions = $validFileExtensions;
        
        parent::__construct($recursiveIterator);
    }
    
    public function accept() {
        return in_array(pathinfo($this->current(), PATHINFO_EXTENSION), $this->validFileExtensions);
    }
}

foreach(new RecursiveFileExtensionFilterIterator(new RecursiveDirectoryIterator('.'), array('php')) as $file) {
    echo $file->getFilename(), "\r\n";
}

That is sexy, but I would go for simpler.  Either pass in an array of file extensions, or explode for one and use in_array() if you're looping through a directory with readdir() or some such.  But I would probably glob():

 

function loadFiles($directory, $extensions) {
    $pattern = '{*.' . implode(',*.', explode(',', $extensions)) . '}';
    return glob($directory . '/' . $pattern, GLOB_BRACE);
}
$some_var = loadFiles(DATA_DIRECTORY, "csv,xls,etc");

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.