0

I am stuck with the following problem. I have the following recursive reading directory php function.

<?php

//a simple file tree traversal - takes in a path and returns a nested array

$delim = strstr(PHP_OS, "WIN") ? "\\" : "/";

function retrieveTree($path)  {

global $delim;

if ($dir=@opendir($path)) {

    while (($element=readdir($dir))!== false) {

        if (is_dir($path.$delim.$element) && $element!= "." && $element!= "..") {

            $array[$element] = retrieveTree($path.$delim.$element);

        } elseif ($element!= "." && $element!= "..") {

            $array[] = $element;

        }

    }

    closedir($dir);

}

return (isset($array) ? $array : false);

}

?>

This function is taken from http://devzone.zend.com/283/recursion-in-php-tapping-unharnessed-power/ It reads an directory and it's subdirectories, for example:

foo/baz
foo/baz/bop
foo/baz/bop/file4.txt
foo/baz/file2.txt
etc/

And it will create an array with directory and files format.

It works well but I like to create a directory tree. How could I change this function to create a list like structure as follows.

<ul>
    <li>foo
        <ul>
            <li>baz
                 ...
        </ul>
    </li>
             ...
    <li>etc
         ...
</ul>

I tried alot of things with no success.

Minahalmon
  • 131
  • 2
  • 11
  • 1
    similar http://stackoverflow.com/questions/10779546/recursiveiteratoriterator-and-recursivedirectoryiterator-to-nested-html-lists/10780023#10780023 – Musa Jun 09 '13 at 16:45
  • 1
    Note that this function you found is much more complicated than it needs to be. There is Iterators for this kind of work: http://stackoverflow.com/questions/2418068/php-spl-recursivedirectoryiterator-recursiveiteratoriterator-retrieving-the-full/2655620#2655620 – Gordon Jun 09 '13 at 16:46
  • @Gordon thanks for the answers, I had a feeling the function was complicated. The link is very useful. I have never used new RecursiveIteratorIterator before. – Minahalmon Jun 10 '13 at 11:39
  • @Musa Great function you created. Is there a way to only show directories in that list. Excluding the files. – Minahalmon Jun 10 '13 at 11:39
  • 1
    You can just check if the current item is a directory `$object->isDir()` and add the element of not. – Musa Jun 10 '13 at 21:21
  • @Musa thanks I am almost sad to say but I have another question. Your function works nice. But I wonder how to put a text after a node using the $dom structure. example: `
  • Oak
  • ` – Minahalmon Jun 15 '13 at 10:55