PHP SPL RecursiveDirectoryIterator RecursiveIteratorIterator restoring a full tree

how can i get the full directory tree using SPL ?

+5
source share
2 answers

By default, RecursiveIteratorIterator will use LEAVES_ONLY for the second __construct argument. This means that it will only return files. If you want to include files and directories (at least what I consider to be a full directory), you will need:

 $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST ); 

and then you can foreach over it. If you want to return a directory tree instead of outputting it, you can store it in an array, for example.

 foreach ($iterator as $fileObject) { $files[] = $fileObject; // or if you only want the filenames $files[] = $fileObject->getPathname(); } 

You can also create an array of $fileObjects without foreach by doing:

 $files[] = iterator_to_array($iterator); 

If you only need the returned directories, foreach over $iterator as follows:

 foreach ($iterator as $fileObject) { if ($fileObject->isDir()) { $files[] = $fileObject; } } 
+18
source

You can simply or do whatever you want.

 foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $file) { /* @var $file SplFileInfo */ //... } 
+3
source

All Articles