I am working with PHP's SPL Recursive Iterators, they are rather confusing to me though but I am learning.
I am using them in a project where I need to recursively grab all files and exclude folders from my result. I was initially using this method...
$directory = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($directory,
RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isDir()) {
//skip directories
//continue;
}else{
// process files
}
}
But then a SO user suggested that I use this method instead so that I would not need to use the isDir()
method in my loop...
$directory = new RecursiveDirectoryIterator($path,
RecursiveDirectoryIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($directory,
RecursiveIteratorIterator::LEAVES_ONLY);
Notice that I used RecursiveDirectoryIterator::SKIP_DOTS
in the RecursiveDirectoryIterator
constructor which is supposed to skip folders or .
and ..
Now I am confused because after some test, even without using the RecursiveDirectoryIterator::SKIP_DOTS
it seems to not show them, I am using Windows could that be the reason, do the dots only show up on a Unix type system? Or am I confused to the point that I am missing something?
Also by using RecursiveIteratorIterator::LEAVES_ONLY
instead of RecursiveIteratorIterator::CHILD_FIRST
it will stop folders from showing up in my result which is what I want but I don't understand why? The documentation has no information on this
An iterator contains a list of items and provides methods to loop through them. It keeps a pointer to one of the elements in the list. Each item in the list should have a key which can be used to find the item.
Iterators encourage you to process data iteratively, instead of buffering it in memory. While it is possible to do this without iterators, the abstractions they provide hide the implementation which makes them really easy to use.
A leaf is an item in the tree which does not have any further items hanging off of it, i.e. it's the end of a branch. By definition, files fit this description.
-- folder
|
|- folder
| |
| |- file <- a leaf
| |
| -- folder
| |
| -- file <- another leaf
|
-- file <- yet another leaf
By setting the RecursiveIteratorIterator
to "leaf only" mode, it's going to skip over any item that's not a leaf.
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