2

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.

Current wrong output

This is what I am trying to achieve

this output

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");
?>
2
  • 1
    What you want is not valid HTML: <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. Commented Feb 21, 2019 at 20:11
  • @trincot is right. You can see a nested list example on w3school Commented Feb 21, 2019 at 20:37

1 Answer 1

-1

max514, this has already been answered here with a full working example.

RecursiveIteratorIterator and RecursiveDirectoryIterator to nested html lists

Sign up to request clarification or add additional context in comments.

6 Comments

This should have been a comment. Once you have the required reputation you can vote to close a question as duplicate.
trincot, I understand. I don't have the reputation yet to comment or suggest duplicate, so I wrote it as an answer.
Still, that is not a valid reason to post it as an answer. There is a reason why reputation requirements exist. To work around them in this way is not their purpose.
trincot, ok so for people looking for help, and it is already answered in another stack, I am suppose to just move along and not help and ignore the fact they need help because I lack reputation. Sounds reasonable. (sigh)
Sorry brother i'm afraid DomDocument method will not work for this. I'll append div tags and href link to every ul for bootstrap sorry i didnt mentioned that in the question pls remove marked as duplicate.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.