$dir = new RecursiveDirectoryIterator('/path/to/directory'); $iter = new RecursiveIteratorIterator($dir); foreach ($iter as $file) { if ($file->isFile()) { echo $iter->getFilename() . "\n"; } }
$dir = new RecursiveDirectoryIterator('/path/to/directory'); $filter = new RecursiveCallbackFilterIterator($dir, function($file) { return strpos($file->getFilename(), '.txt') !== false; }); $iter = new RecursiveIteratorIterator($filter); foreach ($iter as $file) { if ($file->isFile()) { echo $iter->getFilename() . "\n"; } }In this example, we use a RecursiveCallbackFilterIterator to filter the files being iterated over by extension. Specifically, we only want to include files with a .txt extension. We check the extension using strpos() and then create a new RecursiveIteratorIterator to iterate over the filtered files. Inside the loop, we call getFilename() as before to retrieve the filename of each file. Package/library: The RecursiveIteratorIterator class is part of the PHP Standard Library and does not require any external packages or libraries.