How can I retrieve the full directory tree using SPL
, possibly using RecursiveDirectoryIterator
and RecursiveIteratorIterator
?
Asked
Active
Viewed 6,194 times
6

Félix Adriyel Gagnon-Grenier
- 8,422
- 10
- 52
- 65

kmunky
- 15,383
- 17
- 53
- 64
2 Answers
19
By default, the RecursiveIteratorIterator
will use LEAVES_ONLY
for the second argument to __construct
. This means it will return files only. If you want to include files and directories (at least that's what I'd consider a full directory tree), you'd have to do:
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST
);
and then you can foreach
over it. If you want to return the directory tree instead of outputting it, you can store it in an array, e.g.
foreach ($iterator as $fileObject) {
$files[] = $fileObject;
// or if you only want the filenames
$files[] = $fileObject->getPathname();
}
You can also create the array of $fileObjects
without the foreach
by doing:
$files[] = iterator_to_array($iterator);
If you only want directories returned, foreach
over the $iterator
like this:
foreach ($iterator as $fileObject) {
if ($fileObject->isDir()) {
$files[] = $fileObject;
}
}

Gordon
- 312,688
- 75
- 539
- 559
3
You can just, or do everythng that you want
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $file)
{
/* @var $file SplFileInfo */
//...
}

nefo_x
- 3,050
- 4
- 27
- 40
-
Hi, what I don't understand is, how - from the PHP doc of [RecursiveIteratorIterator](http://php.net/manual/fr/class.recursiveiteratoriterator.php) - do you deduct that `$file` is of type SplFileInfo ? – martin Dec 29 '16 at 20:27