【问题标题】:Get filenames of images in a directory获取目录中图像的文件名
【发布时间】:2012-01-14 22:20:12
【问题描述】:

如何使用 PHP 从文件夹/目录中获取图像的标题(例如 abc.jpg)并将它们存储在数组中。

例如:

a[0] = 'ac.jpg'
a[1] = 'zxy.gif'

等等

我将在幻灯片放映中使用数组。

【问题讨论】:

    标签: php opendir


    【解决方案1】:

    这当然是可能的。查看the documentation for opendir 并将每个文件推送到结果数组。如果您使用的是 PHP5,请查看 DirectoryIterator。这是一种遍历目录内容的更流畅、更简洁的方式!

    编辑:建立在opendir上:

    $dir = "/etc/php5/";
    
    // Open a known directory, and proceed to read its contents
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            $images = array();
    
            while (($file = readdir($dh)) !== false) {
                if (!is_dir($dir.$file)) {
                    $images[] = $file;
                }
            }
    
            closedir($dh);
    
            print_r($images);
        }
    }
    

    【讨论】:

      【解决方案2】:

      'scandir' 这样做:

      $images = scandir($dir);
      

      【讨论】:

      • scandir 比 glob 最安全,因为目录可以包含正则表达式字符
      • 为什么这不是公认的答案?!美丽的一个班轮。
      • 它也返回“.”和“..”有没有更好的方法来循环跳过它?
      【解决方案3】:

      一个班轮:-

      $arr = glob("*.{jpg,gif,png,bmp}", GLOB_BRACE) 
      

      【讨论】:

        【解决方案4】:

        glob in php - 查找匹配模式的路径名

        <?php
            //path to directory to scan
            $directory = "../images/team/harry/";
            //get all image files with a .jpg extension. This way you can add extension parser
            $images = glob($directory . "{*.jpg,*.gif}", GLOB_BRACE);
            $listImages=array();
            foreach($images as $image){
                $listImages=$image;
            }
        ?>
        

        【讨论】:

          猜你喜欢
          • 2022-09-24
          • 1970-01-01
          • 1970-01-01
          • 2021-03-18
          • 2021-12-04
          • 2011-03-05
          • 2014-11-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多