How to list folders and files in an HTML list using RecursiveDirectoryIterator

Hi all,

I can’t seem to figure out how to get the proper list structure and naming for the directories (I get Array). Also, is there a way to filter out unwanted files by their extensions using this method.

Thanks.

function buildDirTree( RecursiveDirectoryIterator $iterator ) {
	$tree = array();
	
	foreach ( $iterator as $fileinfo ) { 		
       	
		 if ( $fileinfo->isDir() ) {
            		$tree .= buildDirTree( $iterator->getChildren() );		
        		} else {
           	        $tree .= '<li><a href="' . $iterator->getSubPath() . '/' . $fileinfo->getFilename() .'">' . $fileinfo->getFilename() . '</a></li>';
       		 }
 	 }	
		
	return '<ul>' . $tree . '</ul>';
}

print( buildDirTree( new RecursiveDirectoryIterator('.') ) );

There are a few ways to do it. start your quest here:

http://php.net/manual/en/function.scandir.php

and

http://php.net/manual/en/function.glob.php

Regarding filtering out iterable entries, you can use FilterIterator for that. :slight_smile: