我不想扫描目录及其子目录中的所有文件。并在数组中获取它们的路径。类似于数组中目录中文件的路径将只是
路径->text.txt
而子目录中文件的路径将是
somedirectory/text.txt
我可以扫描单个目录,但它返回所有文件和子目录,没有任何区别。
if ($handle = opendir('fonts/')) {
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo "$entry<br/>";
}
closedir($handle);
}
获取目录和子目录中所有文件及其路径的最佳方法是什么?
使用SPL中的DirectoryTerator可能是最好的方法:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach ($it as $file) echo $file."'n";
$file
是一个SPLFileInfo对象。它的__toString()方法将为您提供文件名,但还有其他几个方法也很有用!
有关更多信息,请参阅:http://www.php.net/manual/en/class.recursivedirectoryiterator.php
使用is_file()
和is_dir()
:
function getDirContents($dir)
{
$handle = opendir($dir);
if ( !$handle ) return array();
$contents = array();
while ( $entry = readdir($handle) )
{
if ( $entry=='.' || $entry=='..' ) continue;
$entry = $dir.DIRECTORY_SEPARATOR.$entry;
if ( is_file($entry) )
{
$contents[] = $entry;
}
else if ( is_dir($entry) )
{
$contents = array_merge($contents, getDirContents($entry));
}
}
closedir($handle);
return $contents;
}