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");
$dom->appendChild($list);
$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());
$node->appendChild($li);
}
elseif ($objects->getDepth() > $depth){
//the depth increased, the last li is a non-empty folder
$li = $node->lastChild;
$ul = $dom->createElement('ul');
$li->appendChild($ul);
$ul->appendChild($dom->createElement('li', $object->getFilename()));
$node = $ul;
}
else{
//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());
$node->appendChild($li);
}
$depth = $objects->getDepth();
}
echo $dom->saveHtml();
The out put will be along the lines of
<ul>
<li>dir1</li>
<li>dir2
<ul>
<li>in dir2</li>
<ul>
<li>file in root</li>
<ul>