I have a directory that has a depth of at least 3 or 4 levels. I'm trying to recurse through the directory tree as deep and generate a HTML unordered nested list.
The code I'm using creates a nested HTML list but it is not in the correct directory depth order. This is what it is currently producing which is not correct.
This is what I am trying to achieve
My current code is below. Which part do I need to modify to make this work?
<?php
function read_dir_tree($parent_dir, $depth = 0){
$str_result = "";
$str_result .= "<li>". dirname($parent_dir) ."</li>";
$str_result .= "<ul>";
if ($handle = opendir($parent_dir))
{
while (false !== ($file = readdir($handle)))
{
if(in_array($file, array('.', '..'))) continue;
if( is_dir($parent_dir . "/" . $file) ){
$str_result .= "<li>" . read_dir_tree($parent_dir . "/" . $file, $depth++) . "</li>";
}
$str_result .= "<li>{$file}</li>";
}
closedir($handle);
}
$str_result .= "</ul>";
return $str_result;
}
function read_dir($tp){
$link = ($tp);
echo "<ul>".read_dir_tree($link)."</ul>";
}
?>
I call this PHP from HTML using:
<?php
read_dir("media");
?>


<li>elements are not allowed to have a<li>element as parent. If you do that, the first of the two is considered closed, and so they are siblings. The</li>tag of the parent is then wrongly positioned.