How can PHP be used to dynamically generate a directory tree with expandable and collapsible nodes?
To dynamically generate a directory tree with expandable and collapsible nodes using PHP, you can use a recursive function to traverse the directory structure and output the HTML with JavaScript for expanding and collapsing nodes.
<?php
function generateDirectoryTree($path) {
$tree = '<ul>';
$files = scandir($path);
foreach($files as $file) {
if ($file != '.' && $file != '..') {
$fullPath = $path . '/' . $file;
if (is_dir($fullPath)) {
$tree .= '<li><span class="folder">' . $file . '</span>';
$tree .= generateDirectoryTree($fullPath);
$tree .= '</li>';
} else {
$tree .= '<li><span class="file">' . $file . '</span></li>';
}
}
}
$tree .= '</ul>';
return $tree;
}
echo generateDirectoryTree('path/to/directory');
?>
Related Questions
- How can PHP substr() function be utilized effectively in string manipulation?
- When implementing a feature that involves calculating time intervals in PHP, what are some common pitfalls to avoid in order to ensure accurate and reliable time calculations?
- What is the correct syntax for using if-else statements within an echo command in PHP?