Thread: folder scan
View Single Post
Old 10-11-2010, 07:57 PM   #5 (permalink)
GSmith
Only Human
 
Join Date: Oct 2010
Posts: 5
Thanks: 0
GSmith is on a distinguished road
Default

I'm not entirely sure what you mean, but here's a quick mock up of a modified function using SPL which will recurse through subdirectories, build and return an output string with padding for recursion depth. I'm at work right now, so cut me some slack if it produces unexpected results!
PHP Code:
function dirs($path)
{
    
settype($path'string');
    if (!
is_dir($path) || !is_readable($path))
        return 
FALSE;

    
$output $path PHP_EOL;
    
$padding 2;

    
$it = new RecursiveIteratorIterator(
        new 
RecursiveDirectoryIterator($path),
        
RecursiveIteratorIterator::SELF_FIRST);
    foreach (
$it as $node)
    {
        if (
$it->isDot())
            continue;
        if (!
$node->isReadable())
            continue;
        if (!
in_array($node->getType(), array('dir''file')))
            continue;

        
/*
         * Define padding depending on recursion depth and
         * strip out $path and any leading directory separators
         * from the pathname, appending to $output.
         */
        
$output .= sprintf('% ' . ($it->getDepth() + 1) * $padding 's''') .
            
ltrim(substr_replace($node''0strlen($path)),
                
DIRECTORY_SEPARATOR);

        if (
$node->isDir())
            
$output .= DIRECTORY_SEPARATOR;
        
$output .= PHP_EOL;
    }

    return 
$output;
}

echo 
dirs('.'); 
Output
Code:
.
  directoryiterator.php
  baz/
    baz/baq/
      baz/baq/baz
      baz/baq/bar
      baz/baq/foo
  bar
  foo
  baq/
The filesystem returns files in the order they are stored on disk, so an array is probably more appropriate because we can easily sort it; I'll try and provide an update later today.

RecursiveIteratorIterator and RecursiveDirectoryIterator are the workhorses here. There's also a bit of string manipulation in order to produce that particular output, and you can also define the amount of padding per recursion depth by modifying the $padding variable. The constants PHP_EOL (new line) and DIRECTORY_SEPARATOR (/ or \) are platform-independent and defined by PHP at run-time.

If this is a web application you'll have to insert HTML line breaks by each PHP_EOL and replace leading spaces with   to see the formatting using an text/html MIME type. For example:
PHP Code:
echo nl2br(str_replace(' '' 'dirs('.'))); 
I hope I haven't misunderstood your question.

Cheers.
GSmith is offline  
Reply With Quote
The Following User Says Thank You to GSmith For This Useful Post:
medvirus (10-11-2010)