」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 PHP 中從目錄中檢索檔案名稱?

如何在 PHP 中從目錄中檢索檔案名稱?

發佈於2024-11-07
瀏覽:337

How to Retrieve Filenames from a Directory in PHP?

從 PHP 中的目錄中擷取檔案

如何在 PHP 中存取目錄中的檔案名稱?事實證明,確定正確的命令具有挑戰性。這個問題旨在為尋求類似解決方案的個人提供幫助。

PHP提供了幾種從目錄獲取文件清單的方法:

DirectoryIterator(建議)

此類允許對目錄中的文件進行迭代:

foreach (new DirectoryIterator('.') as $file) {
    if($file->isDot()) continue;
    print $file->getFilename() . '
'; }

scandir

此函數檢索目錄中的文件和目錄數組:

$files = scandir('.');
foreach($files as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '
'; }

readdir 和opendir

此函數組合提供對目錄句柄的存取:

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if($file == '.' || $file == '..') continue;
        print $file . '
'; } closedir($handle); }

glob

此函數對於基於模式匹配文件很有用:

foreach (glob("*") as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '
'; }

附加說明

glob 允許使用模式進行更複雜的文件匹配,例如文本文件的''.txt' 或'image_ ' 對於以前綴'image_' 開頭的檔案。

版本聲明 本文轉載於:1729248137如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3