RecursiveIteratorIterator and RecursiveDirectoryIterator to nested html lists

Here is one using DomDocument

The basic idea is the contents of each directory is represented by a <ul> and each element in the directory by a <li>
If element is a non-empty directory it will contain a <ul> to represent its contens and so on.

$path = $_SERVER['DOCUMENT_ROOT'].'/test';
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
$dom = new DomDocument("1.0");
$list = $dom->createElement("ul");
$node = $list;
$depth = 0;
foreach($objects as $name => $object){  
    if ($objects->getDepth() == $depth){
//the depth hasnt changed so just add another li
        $li = $dom->createElement('li', $object->getFilename());
    elseif ($objects->getDepth() > $depth){
//the depth increased, the last li is a non-empty folder 
        $li = $node->lastChild;
        $ul = $dom->createElement('ul');
        $ul->appendChild($dom->createElement('li', $object->getFilename()));
        $node = $ul;
//the depth decreased, going up $difference directories
        $difference = $depth - $objects->getDepth();
        for ($i = 0; $i < $difference; $difference--){
            $node = $node->parentNode->parentNode;
        $li = $dom->createElement('li', $object->getFilename());
    $depth = $objects->getDepth();
echo $dom->saveHtml();

The out put will be along the lines of

            <li>in dir2</li>
    <li>file in root</li>

Leave a Comment