Recursive directory iteration with PHP Filesystem API
I have a small stuff to do this morning related to php filesystem api, warming memcached for static files and php template to reduce I/O process overhead in front-end application
$dir = '/path/to/some/dir';
$flags = FilesystemIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS;
$iterator = new RecursiveDirectoryIterator($dir, $flags);
$result = array();
foreach ($iterator as $file) {
$result[] = $file->getFilename();
}
print_r($result);
The result will be list of files and directories exist in `$dir`, somehow i need a recursive iterator, luckily php has it all, with small pimp I can have it, just before line where `$result` declaration, I add this line
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
bingo! now it running recursively, i need some filtering here since i only need files with `.txt` or `.html` files, currently it returned all files and directories exists in `$dir` so i created a new iterator filtering class as below
class FilterTxtHtml extends FilterIterator {
public function accept() {
$fileinfo = $this->getInnerIterator()->current();
if (preg_match('/\.(txt|html)$/', $fileinfo)) {
return true;
}
return false;
}
}
save it somewhere, include it and put this line before `$result` declaration,
$iterator = new FilterTxtHtml($iterator);
final code as below:
$dir = '/path/to/some/dir';
$flags = FilesystemIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS;
$iterator = new RecursiveDirectoryIterator($dir, $flags);
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
$iterator = new FilterTxtHtml($iterator);
$result = array();
foreach ($iterator as $file) {
$result[] = $file->getFilename();
}
print_r($result);
Easy enough.





Hi there to all, how is the whole thing, I think every one
is getting more from this web page, and your views are fastidious in support
of new visitors.
Appreciation to my father who informed me on the topic of this weblog, this blog is
in fact awesome.
Magnificent website. A lot of useful info here. I am sending it to some friends ans also sharing in delicious.
And certainly, thanks on your sweat!