【发布时间】:2012-11-06 20:04:21
【问题描述】:
我必须列出目录中的所有文件和文件夹:
$images = array();
$dirs = array();
$dir = new DirectoryIterator($upload_dir_real);
foreach ($dir as $file) {
if ($file->isDot()) {
continue;
}
if ($file->isDir()) {
// dir
$scanned_dirs[] = $file->getPath();
continue;
} else {
// file
//echo $file->getFilename() . "<br>\n";//DEBUG
$realfile = $file->getFilename() . "<br>\n";
$realpath = $file->getPathname();
echo realpath($realfile);//DEBUG
$file->getFilename();
$images[] = realpath( $realpath );
}
}
这很好用(没有错误),但当然只计算了根,所以我尝试了递归:
$images = array();
$dirs = array();
$dir = new RecursiveDirectoryIterator($upload_dir_real);
foreach ($dir as $file) {
if ($file->isDot()) {
continue;
}
if ($file->isDir()) {
// dir
$scanned_dirs[] = $file->getsubPath();
continue;
} else {
// file
//echo $file->getFilename() . "<br>\n"; //DEBUG
$realfile = $file->getsubFilename() . "<br>\n";
$realpath = $file->getsubPathname();
echo realpath($realfile);//DEBUG
$file->getFilename();
$images[] = realpath( $realpath );
}
}
基本上,我将getPath(); 更改为getsubPath()(和等效项)。问题是它给了我一个错误:
Fatal error: Call to undefined method SplFileInfo::isDot() in blah blah path
所以我搜索了一段时间,发现了这个:
Why does isDot() fail on me? (PHP)
这基本上是同样的问题,但是当我尝试时,我得到了这个错误:
Fatal error: Class 'FilesystemIterator' not found in in blah blah path
问题:
1 - 为什么其他接受的答案中描述的方法对我不起作用? 2 - 在同一个答案中,以下代码是什么:
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$pathToFolder,
FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_SELF));
这实际上调用了两次RecursiveIteratorIterator?我的意思是,如果它是递归的,它就不能递归两次:-)
2b - 为什么FilesystemIterator 找不到,即使 PHP 手册声明(据我了解)它是递归迭代器所基于的一部分?
(这些问题是因为我想更好地理解,而不仅仅是复制和粘贴答案)。
3 - 有没有更好的方法来跨平台列出所有文件夹和文件?
【问题讨论】:
-
FilesystemIterator是在 PHP 5.3 中引入的,API 文档仅代表基于它的RecursiveDirectoryIterator的当前状态。在上一个 sn-p 中,您没有使用两次 RII,而是有一个 RII 和一个 RDI。 -
你用的是什么版本的PHP
-
ooh .. 我错过了 RII 和 RDI - 谢谢,(也解释了 php 版本 - 我使用 5.2.9)但仍然 - 我如何使用 is_dot 或等效项?如何让这个功能发挥作用?