Scan files in a directory and sub-directory and store their path in array using php(使用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
路径 -> 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."
";
$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
这篇关于使用php扫描目录和子目录中的文件并将其路径存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用php扫描目录和子目录中的文件并将其路径存储在数组中


- PHP - if 语句中的倒序 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01