RecursiveFileExtensionFilteredIterator – rolls right off the tongue, right?

Recently I had the need to find all of the files in a fairly big directory structure that were web pages – in my case, files with the .php and .html extensions. There were hundreds of directories and thousands of files to go through, so I decided to write a php script to find the files and then execute some code on the resulting files.

I abstracted out the code to find files matching a particular extension and have posted the (minimal) code on Github as RecursiveFileExtensionFilteredIterator. The 20 or so lines of code makes use of a couple of PHP’s SPL iterators including the Recursive Directory Iterator, the the Recursive Iterator Iterator, and the Filter Iterator. The result of this is a simple class that allows you to loop through a directory recursively to find only files that match a particular set of extensions, returning a SplFileInfo object for each file. Here’s a simple example that prints out all of the paths:

$path = '/path/to/starting/directory';
$extensions = array('php','html');
$files = new RecursiveFileExtensionFilteredIterator($path, $extensions);
foreach($files as $file) {
	echo $file->getPathname() . "\n";

that’s it – short and sweet.