If you want a flat iteration of a directory structure, try combining the RecursiveDirectoryIterator drived by RecursiveIteratorIterator. This is how the skeleton of the iteration could look like:
$start_dir="/some/path";
$rit = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$start_dir,
FilesystemIterator::KEY_AS_PATHNAME |
FilesystemIterator::CURRENT_AS_FILEINFO |
FilesystemIterator::SKIP_DOTS
),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($rit as $path => $fileinfo) {
$level = $rit->getDepth();
if ($fileinfo->isDir()) {
print "[{$level}] in dir:{$path}\n";
} else {
print "[{$level}] file: {$path}\n";
}
}
This might look a little scary, but it’s actually relative straightforward:
-
The
RecursiveDirectoryIterator
will do the bulk of the work, however if you iterate over it you will get the selected directory’s nodes as you would get by a a simpleDirectoryIterator
. -
However since it implements the
RecursiveIterator
interface, you can drive it by aRecursiveIteratorIterator
and save yourself the “has child? recurse into … ” conditionals in your loops, this is what theRecursiveIteratorIterator
will do for you and give back an iterator that looks flat, but it actually recurses into the child nodes. You can use thegetDepth
to detect when a sub-iteration with leaf nodes starts, and you can use the full path name to detect how the directories are changing.
0
solved Loop dirs and write xml of content files in php [closed]