简体   繁体   English

使用RecursiveIteratorIterator列出文件夹中的文件很棒。 我也可以获得父路径和完整路径吗?

[英]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中的完美答案所列目录中的所有文件

  • I'm setting the root of the search to ".." and all filenames get a prefix of "../". 我将搜索的根设置为“..”,并且所有文件名都获得前缀“../”。 How can I get the filename only? 我怎样才能获得文件名?
  • How can I get, in addition to the filename, its parent folder name? 除文件名外,如何获取其父文件夹名称?
  • ...and how can I get the full path of the filename? ...我怎样才能获得文件名的完整路径?

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类型的对象,可以像字符串一样使用,但它也提供了更详细的信息:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM