2011-06-04 48 views

回答

13

可以使用glob()功能:

例01:

<?php 
    // read all files inside the given directory 
    // limited to a specific file extension 
    $files = glob("./ABC/*.txt"); 
?> 

例02:

<?php 
    // perform actions for each file found 
    foreach (glob("./ABC/*.txt") as $filename) { 
    echo "$filename size " . filesize($filename) . "\n"; 
    } 
?> 

例03:使用RecursiveIteratorIterator

<?php 
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator("../")) as $file) { 
    if (strtolower(substr($file, -4)) == ".txt") { 
     echo $file; 
    } 
} 
?> 
+0

Hrrm ...這是如何把他們放入數組? – 2011-06-04 01:44:33

+0

@AJ,'glob'返回一個aray – Petah 2011-06-04 01:45:38

+0

我添加了頂部的示例$文件將是txt文件路徑的數組 – 2011-06-04 01:46:35

1

scandir列出指定路徑內的文件和目錄。

+0

這包括子目錄也不過......不知道OP希望呢? – 2011-06-04 01:45:13

2

試試這個:

if ($handle = opendir('.')) { 
    $files=array(); 
    while (false !== ($file = readdir($handle))) { 
     if(is_file($file)){ 
      $files[]=$file; 
     } 
    } 
    closedir($handle); 
} 
0

如果你的文本文件是你的所有的文件夾內,最簡單的方法是使用SCANDIR,像這樣:

<?php 
$arr=scandir('ABC/'); 
?> 

如果您有其他的文件,你應該使用水珠在勞倫斯的回答。

1

這裏是在此基礎上article的基準測試中最高效方式:

function getAllFiles() { 
    $files = array(); 
    $dir = opendir('/ABC/'); 
    while (($currentFile = readdir($dir)) !== false) { 
     if (endsWith($currentFile, '.txt')) 
      $files[] = $currentFile; 
    } 
    closedir($dir); 
    return $files; 
} 

function endsWith($haystack, $needle) { 
    return substr($haystack, -strlen($needle)) == $needle; 
} 

只使用getAllFiles()函數,你甚至可以修改它採取的文件夾路徑和/或需要擴展,很簡單。

+0

嗨,你將如何迴應與文件名? – user3771102 2014-09-09 12:14:10

+1

@ user3771102返回的'$ files'數組包含所有帶擴展名的文件名,並且您可以像foreach($ files作爲$ fileName){echo $ fileName;}'那樣'foreach'&echo它們,或者如果您只想證明它正在工作,你可以在 – AbdelHady 2014-09-09 16:29:29

0
$dir = "your folder url"; //give only url, it shows all folder data 

if (is_dir($dir)){ 
    if ($dh = opendir($dir)){ 
     while (($file = readdir($dh)) !== false){ 
      if($file != '.' and $file != '..'){ 
       echo $file .'<br>'; 
      } 
     } 
     closedir($dh); 
    } 
} 

輸出:

xyz 
abc 
2017 
motopress 
+0

以上的內部'if if'裏面回顯'$ currentFile',你沒有回答問題 - 在「限於一個特定的文件擴展名」部分 – YakovL 2017-07-22 20:56:43

+0

請給出一些解釋你的答案如何解決原始問題。 – 2017-07-22 20:58:21

相關問題