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');
?>