phirschybar
phirschybar

Reputation: 8589

Out of the box directory structure component for php

Anybody know of a ready-made php class which can read a file-system directory recursively (including all files and sub-directories) and return an array or object or JSON string or XML of the structure?

I would do this myself but a client just called and is insisting on it being done today. Yay.

Upvotes: 1

Views: 302

Answers (3)

hakre
hakre

Reputation: 198119

You can make use of the in-build RecursiveDirectoryIterator­Docs class to create your wished outcome. In the following example an hierarchical array is created:

$dir = '.';

$dirit = new RecursiveDirectoryIterator($dir);
$it = new RecursiveIteratorIterator($dirit);
$array = array();
foreach($it as $file)
{
    $path = substr($file, strlen($dir)+1);
    $parts = explode(DIRECTORY_SEPARATOR, $path);
    $filename = array_pop($parts);
    $dirname = implode(DIRECTORY_SEPARATOR, $parts);
    $build = &$array;
    foreach($parts as $part)
    {
        if (!isset($build[$part])) $build[$part] = array();
        $build = &$build[$part];
    }
    $build[] = $filename;
    unset($build);
}

$array will then contain the listing:

Array
(
    [0] => .buildpath
    [1] => .project
    [.settings] => Array
        (
            [0] => org.eclipse.php.core.prefs
        )

    [array] => Array
        (
            [0] => array-keys.php
            [1] => array-stringkey-explode.php
        )
)

Using json_encode­Docs can simple turn this into something like:

json_encode($array);

{"0":".buildpath","1":".project",".settings":["org.eclipse.php.core.prefs"],"array":["array-keys.php","array-stringkey-e
xplode.php"]}

As I've written in a comment above, glob can be useful, too.

Upvotes: 2

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

You could simply build it yourself either using globals (yuk) or an array merging technique. Here's a basic:

function recursiveListing($currentDir){
    $results = array();
    $dh = opendir($currentDir);
    while(($f = readdir($dh)) !== false){
        if($f == '.' || $f == '..'){ continue; }
        $results[] = $currentDir.'/'.$f;
        if(is_dir($currentDir.'/'.$f)){
            $results = array_merge($results, recursiveListing($currentDir.'/'.$f));
        }
    }
    return $results;
}

This should get your started and should build a list of full paths. Returning this as json is relatively easy with json_encode(). For XML, you can output it yourself or build a simple looping function.

Upvotes: 1

Rudu
Rudu

Reputation: 15892

Well there's a code-fragment in the comments page of the PHP manual for dir for recursively reviewing the contents of a directory (and sub directories) ;) Instead of the echo statements, simply load up an array and return that (so it would be an array of arrays). You'd need to filter for . and .. but otherwise it's mostly done for you.

Upvotes: 1

Related Questions