Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve the full directory tree using SPL?

Tags:

php

spl

How can I retrieve the full directory tree using SPL, possibly using RecursiveDirectoryIterator and RecursiveIteratorIterator?

like image 867
kmunky Avatar asked Mar 10 '10 15:03

kmunky


People also ask

How do I show directory trees in Ubuntu?

You need to use command called tree. It will list contents of directories in a tree-like format. It is a recursive directory listing program that produces a depth indented listing of files. When directory arguments are given, tree lists all the files and/or directories found in the given directories each in turn.

How can I get directory file in PHP?

The scandir() function returns an array of files and directories of the specified directory.

What is a tree directory?

A tree or tree directory structure is a hierarchical data structure that organizes data elements, called nodes, by connecting them with links, called branches. This structure is used to help display large amounts of information in an easy to read format.


2 Answers

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

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

and then you can foreach over it. If you want to return the directory tree instead of outputting it, you can store it in an array, e.g.

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

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

$files[] = iterator_to_array($iterator);

If you only want directories returned, foreach over the $iterator like this:

foreach ($iterator as $fileObject) {
    if ($fileObject->isDir()) {
        $files[] = $fileObject;
    }
}
like image 58
Gordon Avatar answered Oct 26 '22 08:10

Gordon


You can just, or do everythng that you want

foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $file)
{
    /* @var $file SplFileInfo */
    //...
}
like image 45
nefo_x Avatar answered Oct 26 '22 07:10

nefo_x