【问题标题】:Scan files in a directory and sub-directory and store their path in array using php扫描目录和子目录中的文件并使用php将它们的路径存储在数组中
【发布时间】:2012-02-10 20:18:56
【问题描述】:

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

路径 -> 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);
    }

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

【问题讨论】:

    标签: php directory


    【解决方案1】:

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

    【讨论】:

    • 它返回一个空数组。 ://
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多