I have a tree of directories, sub-directories, and files (in some but not all the directories). Here's an example of the whole tree:
/food
/food/drinks
/food/drinks/water.html
/food/drinks/milk.html
/food/drinks/soda.html
/food/entrees
/food/entrees/hot
/food/entrees/hot/hamburger.html
/food/entrees/hot/pizza.html
/food/entrees/cold
/food/entrees/cold/icecream.html
/food/entrees/cold/salad.html
/cosmetics
/cosmetics/perfume
/cosmetics/perfume/chic.html
/cosmetics/perfume/polo.html
/cosmetics/perfume/lust.html
/cosmetics/lipstick
/cosmetics/lipstick/colors
/cosmetics/lipstick/colors/red.html
/cosmetics/lipstick/colors/pink.html
/cosmetics/lipstick/colors/purple.html
OK, From a php script in the '/' directory, I want to recurse or traverse this directory tree and print the tree like this:
<ul>
<li>food</li>
<ul>
<li>drinks</li>
<ul>
<li>water.html</li>
<li>milk.html</li>
<li>soda.html</li>
</ul>
<li>entrees</li>
<ul>
<li>hot</li>
<ul>
<li>hamburger.html</li>
<li>pizza.html</li>
</ul>
<li>cold</li>
<ul>
<li>icecream.html</li>
<li>salad.html</li>
</ul>
</ul>
</ul>
<li>cosmetics</li>
<ul>
<li>perfume</li>
<ul>
<li>chic.html</li>
<li>polo.html</li>
<li>lust.html</li>
</ul>
<li>lipstick</li>
<ul>
<li>colors</li>
<ul>
<li>red.html</li>
<li>pink.html</li>
<li>purple.html</li>
</ul>
</ul>
</ul>
</ul>
PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.
The scandir() function returns an array of files and directories of the specified directory.
What I think you need here is the RecursiveDirectoryIterator from the PHP Standard Library (SPL)
You can then write something similar to the below:
function iterateDirectory($i)
{
echo '<ul>';
foreach ($i as $path) {
if ($path->isDir())
{
echo '<li>';
iterateDirectory($path);
echo '</li>';
}
else
{
echo '<li>'.$path.'</li>';
}
}
echo '</ul>';
}
$dir = '/food';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
iterateDirectory($iterator);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With