I have a folder in which I have some files and sub-folders. I need to return the names of the files or relative address (if the file is in sub-folder) that have a given extension, for example .html.
For example this is structure of given folder:
So the code should return this (in an array ideally):
It's just pulling out names with .html extension, but I really don't how to solve this.
You could use a RecursiveDirectoryIterator to get all files recursively, then filter the result with a RegexIterator to iterate over only the *.html files. To get the relative adress, RecursiveDirectoryIterator::getSubPathname() can be used.
$directory = '../path/to/your/folder';
$all_files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
$html_files = new RegexIterator($all_files, '/\.html$/');
foreach($html_files as $file) {
echo $html_files->getSubPathname(), PHP_EOL;
}
If you really need and array (with iterable objects you often don't), you can easily build one up in the foreach rather than echo-ing each subpath.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With