我不想扫描一个目录及其子目录中的所有文件。在数组中得到他们的路径。就像数组中目录中文件的路径一样,
路径-> text.txt
而子目录中文件的路径将是
目录/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);
}获取目录和子目录中所有文件及其路径的最佳方法是什么?
发布于 2012-01-15 15:19:02
使用SPL中的DirectoryIterator可能是最好的方法:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach ($it as $file) echo $file."\n";$file是SPLFileInfo-object。它的__toString()方法将给出文件名,但是还有其他一些方法也很有用!
有关更多信息,请参见:http://www.php.net/manual/en/class.recursivedirectoryiterator.php
发布于 2012-01-15 15:15:08
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;
}https://stackoverflow.com/questions/8870731
复制相似问题