dir() 類基本用法
read()) {
if ($file === '.' || $file === '..') continue;
$path = "$directory/$file";
if (is_dir($path)) {
echo "<li><font color='#ff00cc'><b>$file</b></font></li>";
tree($path);
} else {
echo "<li>$file</li>";
}
}
echo "</ul>";
$mydir->close();
}
echo "<h2>目錄為粉紅色</h2>";
tree(".");
?>
輸出結構
現代化改寫(SPL)
function tree_spl(string $dir): void {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
echo "<ul>";
foreach ($iterator as $file) {
$depth = $iterator->getDepth();
$indent = str_repeat(" ", $depth);
$icon = $file->isDir() ? "📁 " : "📄 ";
$close = $file->isDir() ? "" : "";
echo "$indent$icon{$file->getBasename()}$close";
}
echo "</ul>";
}