我不得不列出目录中的所有文件和文件夹:目录迭代和递归目录迭代器
$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'的当前状态。在你最后的片段中,你没有使用RII两次,你有一个RII和一个RDI。 – mario
您使用的是什么版本的PHP – Baba
ooh ..我错过了RII和RDI--谢谢,(PHP版本也解释了 - 我使用5.2.9),但仍然 - 我怎样才能使用is_dot或等价的?如何使这个功能起作用? –