首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 遞迴列出目錄所有檔案與資料夾:opendir/readdir 實戰

     編輯:PHP 綜合知識

基本實作



輸出範例

(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 相容跨平台
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved