Skip to content

Instantly share code, notes, and snippets.

@lcherone lcherone/dir.php
Created Sep 16, 2018

Embed
What would you like to do?
Directory Tree Menu
<?php
// https://stackoverflow.com/questions/52348639/how-to-generate-a-recursive-list-of-directories-and-files-with-hyperlinks-to-eac/52348780#52348780
function file_get_listing($path = '')
{
$return = [];
foreach (new IteratorIterator(new DirectoryIterator($path)) as $item) {
if ($item->isDot()) {
continue;
}
$info = [
'text' => $item->getFilename(),
'href' => str_replace('\\', '/', $item->getPathname())
];
if ($item->isDir()) {
$nodes = get_file_listing($item->getPathname());
if (!empty($nodes)) {
$info['nodes'] = $nodes;
}
}
$return[] = $info;
}
return $return;
}
function makeNav($item) {
$return = '<li><a href="'.$item['href'].'">'.$item['text'].'</a>'.PHP_EOL;
if (isset($item['nodes']) && is_array($item['nodes']) && count($item['nodes']) > 0) {
$return .= '<ul>'.PHP_EOL;
foreach ($item['nodes'] as $node) {
$return .= makeNav($node);
}
$return .= '</ul>'.PHP_EOL;
} else {
$return .= '</li>'.PHP_EOL;
}
if (isset($item['nodes']) && is_array($item['nodes']) && count($item['nodes']) > 0) {
$return .= "</li>".PHP_EOL;
}
return $return;
}
$nav = '<ul>';
foreach (file_get_listing('./node_modules') as $item) {
$nav .= makeNav($item);
}
echo $nav.'</ul>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.