php 实现目录树
实现目录树的方法
在PHP中实现目录树功能,可以通过递归或迭代方式遍历文件系统。以下是两种常见的实现方法:
递归方法
递归是处理目录树的自然方式,适合层级不深的结构:

function buildDirectoryTree($path, $prefix = '') {
$tree = '';
$items = scandir($path);
foreach ($items as $item) {
if ($item == '.' || $item == '..') continue;
$fullPath = $path . DIRECTORY_SEPARATOR . $item;
$tree .= $prefix . $item . "\n";
if (is_dir($fullPath)) {
$tree .= buildDirectoryTree($fullPath, $prefix . '│ ');
}
}
return $tree;
}
// 使用示例
echo "<pre>" . buildDirectoryTree('/path/to/directory') . "</pre>";
迭代方法
使用栈结构避免递归可能导致的堆栈溢出:

function buildDirectoryTree($rootPath) {
$stack = array(array($rootPath, 0));
$tree = '';
while (!empty($stack)) {
list($path, $level) = array_pop($stack);
$items = scandir($path);
foreach ($items as $item) {
if ($item == '.' || $item == '..') continue;
$fullPath = $path . DIRECTORY_SEPARATOR . $item;
$tree .= str_repeat(' ', $level) . $item . "\n";
if (is_dir($fullPath)) {
array_push($stack, array($fullPath, $level + 1));
}
}
}
return $tree;
}
输出格式优化
对于HTML展示,可以生成带样式的树形结构:
function htmlDirectoryTree($path, $level = 0) {
$html = '';
$items = scandir($path);
foreach ($items as $item) {
if ($item == '.' || $item == '..') continue;
$fullPath = $path . '/' . $item;
$html .= '<div style="margin-left:' . ($level * 20) . 'px">';
if (is_dir($fullPath)) {
$html .= '[+] ' . htmlspecialchars($item);
$html .= htmlDirectoryTree($fullPath, $level + 1);
} else {
$html .= htmlspecialchars($item);
}
$html .= '</div>';
}
return $html;
}
注意事项
- 路径处理应使用
DIRECTORY_SEPARATOR保证跨平台兼容性 - 对用户提供的路径参数需做安全校验,防止目录遍历攻击
- 大目录结构可能导致性能问题,可考虑分页或延迟加载
- 内存限制可能影响递归深度,可通过
ini_set('memory_limit', ...)调整
扩展功能
实现可折叠的树形结构需要结合JavaScript:
function buildCollapsibleTree($path) {
$items = scandir($path);
$html = '<ul>';
foreach ($items as $item) {
if ($item == '.' || $item == '..') continue;
$fullPath = $path . '/' . $item;
$html .= '<li>';
if (is_dir($fullPath)) {
$html .= '<span class="folder">' . htmlspecialchars($item) . '</span>';
$html .= buildCollapsibleTree($fullPath);
} else {
$html .= htmlspecialchars($item);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
需配合前端JavaScript实现折叠/展开功能。






