首页 文章

扫描目录和子目录中的文件,并使用php将其路径存储在数组中

提问于
浏览
2

我不想扫描目录及其子目录中的所有文件 . 并在阵列中获取他们的路径 . 就像在数组目录中的文件路径一样

path - > 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
"; } closedir($handle); }

使用其路径获取目录和子目录中的所有文件的最佳方法是什么?

2 回答

  • 3

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

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

    $file 是一个SPLFileInfo对象 . 它的__toString()方法将为您提供文件名,但还有其他一些方法也很有用!

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

  • 7

    使用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;
    }
    

相关问题