Loop dirs and write xml of content files in php [closed]

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:

$rit = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator(
        FilesystemIterator::KEY_AS_PATHNAME |
        FilesystemIterator::CURRENT_AS_FILEINFO |

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:

  1. 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 simple DirectoryIterator.

  2. However since it implements the RecursiveIterator interface, you can drive it by a RecursiveIteratorIterator and save yourself the “has child? recurse into … ” conditionals in your loops, this is what the RecursiveIteratorIterator will do for you and give back an iterator that looks flat, but it actually recurses into the child nodes. You can use the getDepth 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.

Browse More Popular Posts

Leave a Comment