基本實作
輸出範例
(2017-01-10 14:39:46) D:/file1.txt
(2017-01-09 10:20:30) D:/folder1
...
進階:遞迴樹狀顯示
function tree(string $dir, int $depth = 0): void {
$dh = opendir($dir);
$indent = str_repeat(' ', $depth);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
echo "$indent<strong>📁 $file</strong><br/>";
tree($path, $depth + 1);
} else {
echo "$indent📄 $file<br/>";
}
}
closedir($dh);
}
tree("D:/");
效能提示
- 大量檔案考慮
RecursiveDirectoryIterator (SPL)
- 生產環境避免直接輸出,建議收集陣列再處理
- Windows 路徑分隔符用
DIRECTORY_SEPARATOR 相容跨平台