Re: Recursive Directory Listing

From: Date: Tue, 04 Nov 2008 15:08:02 +0000
Subject: Re: Recursive Directory Listing
References: 1 2 3 4 5 6 7  Groups: php.general 
Request: Send a blank email to php-general+get-282852@lists.php.net to get a copy of this message
Joe Schaeffer wrote:
Joe, Here is a simplified recursive version of your above statement. <?php $dir = '.'; function displayDir($dir='.') {
       $show = FALSE;
       $results = glob($dir.'/*');
       foreach ( $results AS $entry ) {
               if ( is_dir($entry) && !in_array($entry, array('.', '..')) ) {
                       $dirs[] = $entry;
                       $show = TRUE;
               }
       }
       if ( $show ) {
               echo '<ul>';
               foreach ( $dirs AS $entry ) {
                       echo '<li>', basename($entry);
                       displayDir($entry);
                       echo '</li>';
               }
               echo '</ul>';
       }
} displayDir($dir); ?> Hope this helps -- Jim Lucas
    
Excellent, Jim. Thanks very much for your help. At the risk of straying too far from the original subject/call-for-help, is there a way to flag the *first* time the function runs through a <ul> creation? Though my design doesn't call for it now, I could see the value of styling the first level separately than the sub-directories. Hi,
This one makes use of the SPL and can handle a filter. Maybe not the cleanest way, but good enough for me. function DirectoryIterator($path, $filter = FALSE) { $files = new RecursiveDirectoryIterator($path); foreach($files as $file) {
       if ($filter !== FALSE) {
           if (array_search($file->getFileName(), $filter) !== FALSE) {
               continue;
           }
       }
       if ($file->isDir()) {
           $name = $file->__toString();
           echo str_replace(chr(92), chr(92).chr(92), $name).chr(92).chr(92)."\n";
                     DirectoryIterator($name, $filter);
       }
} } $path = 'C:\\projects\\sites\\www.example.com\\'; DirectoryIterator($path, array('.svn'));

« previous php.general (#282852) next »