[英]Using RecursiveIteratorIterator to list files in folder is great. Can I get the parent path and full path as well?
I need to list all files (which have certain extensions) in a folder and its sub-folders. 我需要在文件夹及其子文件夹中列出所有文件(具有特定扩展名)。 I used RecursiveIteratorIterator as described in @Matthew 's great answer in PHP list all files in directory .
我使用了RecursiveIteratorIterator,如@Matthew在PHP中的完美答案所列目录中的所有文件 。
And one last thing: displaying a file-tree, or maybe all directories that have no sub-directories, are both examples of things that one might want to do when dealing with files. 最后一件事:显示文件树,或者所有没有子目录的目录,都是处理文件时可能想要做的事情的例子。 How would you recommend to pass this data to the client side and how would the data structure look like?
您如何建议将此数据传递给客户端,数据结构如何?
$filename
in that answer is actually not a string. 该答案中的
$filename
实际上不是字符串。 It is an object of type SplFileInfo
which can be used like a string but it also offers much more detailed info: 它是
SplFileInfo
类型的对象,可以像字符串一样使用,但它也提供了更详细的信息:
SplFileInfo::getFilename()
-- filename. SplFileInfo::getFilename()
- filename。 SplFileInfo::getPathname()
-- path to the file SplFileInfo::getPathname()
- 文件的路径 SplFileInfo::getPathInfo()
-- SplFileInfo object for the path SplFileInfo::getPathInfo()
- 路径的SplFileInfo对象 SplFileInfo::getRealPath()
-- canonicalized absolute pathname; SplFileInfo::getRealPath()
- 规范化的绝对路径名; see realpath()
for more info and the difference to Pathname , realpath()
以获取更多信息以及与Pathname的区别, Using this as a base: 以此为基础:
$iter = new RecursiveDirectoryIterator('../');
foreach (new RecursiveIteratorIterator($iter) as $fileName => $fileInfo) {
$fullPath = (string) $fileInfo;
}
Each $fileInfo
will return a SplFileInfo
object. 每个
$fileInfo
都将返回一个SplFileInfo
对象。 The path and filename are easily accessible in addition to a host of other methods. 除了许多其他方法之外,还可以轻松访问路径和文件名。
phpSplFileInfo Object
(
[pathName:SplFileInfo:private] => ./t.php
[fileName:SplFileInfo:private] => t.php
)
I may be mistaken, but to access the parent folder name unless you record it through the tree the simplest would be using dirname
and appending ../
to the path. 我可能会弄错,但要访问父文件夹名称,除非您通过树记录它,最简单的方法是使用
dirname
并将../
附加到路径。
<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::CURRENT_AS_PATHNAME);
foreach ($iterator as $fileinfo) {
echo $iterator->current()->getPathname() . "\n";
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.