Andreas Gohr
Andreas Gohr

Reputation: 4935

RecursiveDirectoryIterator to list directories

I want to use the RecursiveDirectoryIterator to list files and directories recursively. Below is my code.

$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(".", RecursiveDirectoryIterator::SKIP_DOTS));

foreach ($rii as $file){
    if ($file->isDir()) {
        echo "D ".$file->getPathName();
    } else {
        echo "F ".$file->getPathName();
    }
    echo "<br>\n";
}

The problem is that it does not return directories at all. Only files are listed. When I omit the SKIP_DOTS flag, I do get directories but in the form of dir/. and dir/.. which is obviously not what I want.

Now I could of course strip the trailing dots myself, but I wonder if there's a better builtin method I'm not aware of?

Upvotes: 1

Views: 138

Answers (1)

0stone0
0stone0

Reputation: 43983

$rdi = new RecursiveDirectoryIterator('.', RecursiveDirectoryIterator::KEY_AS_PATHNAME | RecursiveDirectoryIterator::SKIP_DOTS);
foreach (new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST) as $file => $info) {
    echo $file."\n";
}

Example files/directory structure

.
|-- a
|   `-- x
|       |-- hbye.txt
|       `-- hello.txt
|-- b
|   `-- a
`-- script.php

4 directories, 3 files

Script output:

./a
./a/x
./a/x/hbye.txt
./a/x/hello.txt
./script.php
./b
./b/a

Upvotes: 1

Related Questions