2011-06-12 38 views
2

我有以下代码片段。我试图列出目录中的所有文件,并让它们可供用户下载。此脚本适用于没有子目录的目录,但如果我想要将文件放入子目录中,则不起作用。它只列出目录名称。我不确定为什么is_dir在我身上失败......我对此感到有点困惑。我相信有更好的方式递归列出所有文件,所以我愿意接受任何建议!在PHP中递归地列出子目录令人烦恼

function getLinks ($folderName, $folderID) { 
$fileArray = array(); 

foreach (new DirectoryIterator(<some base directory> . $folderName) as $file) { 
    //if its not "." or ".." continue 
    if (!$file->isDot()) {    
      if (is_dir($file)) {      
       $tempArray = getLinks($file . "/", $folderID); 
       array_merge($fileArray, $tempArray); 

      } else { 
       $fileName = $file->getFilename();       
      $url = getDownloadLink($folderID, $fileName); 
      $fileArray[] = $url;    
      }      
    } 
} 
+0

[PHP递归目录路径]的可能重复(http://stackoverflow.com/questions/2398147/php-recursive-directory-path) – Gordon 2011-06-12 21:46:36

回答

4

而不是使用DirectoryIterator的,你可以使用RecursiveDirectoryIterator,这对于递归遍历文件结构提供的功能。从文档实例:

$path = realpath('/etc'); 

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); 
foreach($objects as $name => $object){ 
    echo "$name\n"; 
} 

This prints a list of all files and directories under $path (including $path ifself). If you want to omit directories, remove the RecursiveIteratorIterator::SELF_FIRST part.

+0

正是我正在寻找!稍后我会修改我的代码并给它一个提示。谢谢! – thomascirca 2011-06-12 22:28:28

+0

将它代入我的代码中,它效果很好。然而,isDot不再工作。它给出了以下错误:致命错误:调用未定义的方法SplFileInfo :: isDot()。任何想法为什么? – thomascirca 2011-06-12 23:25:57

+0

@thomascirca:你可能想看看这个http://stackoverflow.com/a/13069918/89771,似乎SPL比其他解决方案慢了50%。 – 2012-10-25 14:14:47

0

你应该使用RecursiveDirectoryIterator,但你可能还需要考虑使用Finder组件从Symfony2的。它允许轻松实时过滤(按大小,日期等),包括目录或文件,不包括目录或点文件等。查看Finder.php文件中的docblock以获取说明。