【问题标题】:List all .jpg files from all folders and subfolders列出所有文件夹和子文件夹中的所有 .jpg 文件
【发布时间】:2020-07-02 15:07:51
【问题描述】:

我想列出文件夹和子文件夹中的所有 .jpg 文件。

我有那个简单的代码:

<?php

// directory
$directory = "img/*/";

// file type
$images = glob("" . $directory . "*.jpg");

foreach ($images as $image) {
    echo $image."<br>";
    } 

?>

但这列出了 img 文件夹中的 .jpg 文件和一个向下的文件。

如何扫描所有子文件夹?

【问题讨论】:

  • 也许this 能帮上忙?

标签: php


【解决方案1】:

DirectoryIterator 附带的 PHP 在这种情况下非常有用。 请注意,这个简单的功能可以通过添加文件的整个路径而不是唯一的文件名来轻松改进,并且可能使用其他内容而不是引用。

  /*
   *  Find all file of the given type.
   *  @dir : A directory from which to start the search
   *  @ext : The extension. XXX : Dont call it with "." separator
   *  @store : A REFERENCE to an array on which store the element found.
   * */
  function allFileOfType($dir, $ext, &$store) {
    foreach(new DirectoryIterator($dir) as $subItem) {
      if ($subItem->isFile() && $subItem->getExtension() == $ext)
        array_push($store, $subItem->getFileName());
      elseif(!$subItem->isDot() && $subItem->isDir())
        allFileOfType($subItem->getPathName(), $ext, $store);
    }
  }

  $jpgStore = array();
  allFileOfType(__DIR__, "jpg", $jpgStore);
  print_r($jpgStore);

【讨论】:

    【解决方案2】:

    由于目录可以包含子目录,而子目录又包含子目录,所以我们应该使用递归函数。 glob() 在这里是不够的。这可能对你有用:

    <?php
    function getDir4JpgR($directory) {
      if ($handle = opendir($directory)) {
        while (false !== ($entry = readdir($handle))) {
          if($entry != "." && $entry != "..") {
    
            $str1 = "$directory/$entry";
    
            if(preg_match("/\.jpg$/i", $entry)) {
              echo $str1 . "<br />\n";          
            } else {
              if(is_dir($str1)) {
                 getDir4JpgR($str1);
              }
            }       
          }
        }
        closedir($handle);
      }
    }
    
    //
    // call the recursive function in the main block:
    //
    // directory
    $directory = "img";
    
    getDir4JpgR($directory);
    ?>
    

    我把它放到一个名为 listjpgr.php 的文件中。在我的 Chrome 浏览器中,它提供了以下捕获:

    【讨论】:

      猜你喜欢
      • 2011-05-11
      • 2016-02-26
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      相关资源
      最近更新 更多