在目录和子目录中扫描文件,并使用php将其路径存储在数组中 [英] Scan files in a directory and sub-directory and store their path in array using php

查看:108
本文介绍了在目录和子目录中扫描文件,并使用php将其路径存储在数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想扫描目录及其子目录中的所有文件。并将其路径放在数组中。像数组中目录中文件的路径将只是

I want not scan all the files in a directory and its sub-directory. And get their path in an array. Like path to the file in the directory in array will be just


path - > text.txt

path -> text.txt

而子目录中文件的路径将为

while the path to a file in sub-directory will be


somedirectory / text.txt

somedirectory/text.txt

我可以扫描单个目录,但是它没有任何区别的方式返回所有的文件和子目录。

I am able to scan single directory, but it returns all the files and sub-directories without any ways to differentiate.

    if ($handle = opendir('fonts/')) {
    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry<br/>";
    }


    closedir($handle);
    }

什么是最好的方法来获取目录和子目录中的所有文件,目录及其路径?

What is the best way to get all the files in the directory and sub-directory with its path?

推荐答案

使用SPL中的DirectoryIterator可能是最好的方法:

Using the DirectoryIterator from SPL is probably the best way to do it:

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach ($it as $file) echo $file."\n";

$ file 是一个 SPLFileInfo -object。它的__toString()方法将为您提供文件名,但还有其他几种方法也很有用!

$file is an SPLFileInfo-object. Its __toString() method will give you the filename, but there are several other methods that are useful as well!

有关更多信息,请参阅: http://www.php.net/manual/en/class.recursivedirectoryiterator.php

For more information see: http://www.php.net/manual/en/class.recursivedirectoryiterator.php

这篇关于在目录和子目录中扫描文件,并使用php将其路径存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆