Here\'s my php script:
Store the depth in a variable and check if the variable has been increased or decreased each loop?
If the depth has been increased, you add another <ul>
tag and if it has been decreased you add a closing </ul>
tag.
Each loop would always output the <li>
tags to wrap the filename.
e.g.
$depth = 0;
foreach ($objects as $name => $object) {
$depth2 = $objects->getDepth();
if($depth2 > $depth) { echo '<ul>'; }
echo "<li>" . $object->getFilename() . "</li>";
if($depth2 < $depth) { echo '</ul>'; }
$depth = $depth2;
}
That would need some additional testing and modification to suit your existing code, but hopefully it gives you some ideas.
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>