【问题标题】:Loop code for each file in a directory [duplicate]目录中每个文件的循环代码[重复]
【发布时间】:2011-09-03 13:47:06
【问题描述】:

我有一个图片目录,我想循环并对其进行一些文件计算。可能只是睡眠不足,但我将如何使用 PHP 在给定目录中查找,并使用某种 for 循环遍历每个文件?

谢谢!

【问题讨论】:

    标签: php image filesystems directory


    【解决方案1】:

    scandir:

    $files = scandir('folder/');
    foreach($files as $file) {
      //do your work here
    }
    

    glob 可能更适合您的需求:

    $files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
    foreach($files as $file) {
      //do your work here
    }
    

    【讨论】:

    • $files 变量是否用于避免在foreach 循环中多次调用scandir()?或者我可以直接嵌入没有任何副作用?
    • @Zero3,该变量仅用于可读性。 PHP 将始终在任何 foreach 循环中使用数组的副本,这意味着 scandir() 只会被调用一次。 (而且由于 PHP 使用写时复制,因此这种“复制”也不会出现任何性能问题)。是的,您可以嵌入 scandir() 调用而不会产生任何性能缺陷。
    • 注:scandir() 包括 '.' & '..' 节点。如果您不想通过它们,请从 scandir() 结果中添加检查/删除它们
    【解决方案2】:

    查看DirectoryIterator 类。

    来自该页面上的一个 cmets:

    // output all files and directories except for '.' and '..'
    foreach (new DirectoryIterator('../moodle') as $fileInfo) {
        if($fileInfo->isDot()) continue;
        echo $fileInfo->getFilename() . "<br>\n";
    }
    

    递归版本是RecursiveDirectoryIterator

    【讨论】:

    • 这应该是最佳答案,比 scandir 或 glob 更有用和更现代的方法
    【解决方案3】:

    寻找函数glob()

    <?php
    $files = glob("dir/*.jpg");
    foreach($files as $jpg){
        echo $jpg, "\n";
    }
    ?>
    

    【讨论】:

      【解决方案4】:

      试试GLOB()

      $dir = "/etc/php5/*";  
      
      // Open a known directory, and proceed to read its contents  
      foreach(glob($dir) as $file)  
      {  
          echo "filename: $file : filetype: " . filetype($file) . "<br />";  
      }  
      

      【讨论】:

      • 文件类型不起作用,它返回'file'。
      • @Ajibola 我们在说某些东西不起作用之前检查文档怎么样,对吧? filetype() 返回文件的类型。因此可能的结果是file, dir, char, block, ...。如果您想知道文件的内容类型,可以使用 mime_content_type() 之类的内容。
      【解决方案5】:

      在 foreach 循环中使用 glob 函数来做任何事情。我还在下面的示例中使用了 file_exists 函数来检查目录是否存在,然后再继续。

      $directory = 'my_directory/';
      $extension = '.txt';
      
      if ( file_exists($directory) ) {
         foreach ( glob($directory . '*' . $extension) as $file ) {
            echo $file;
         }
      }
      else {
         echo 'directory ' . $directory . ' doesn\'t exist!';
      }
      

      【讨论】:

        猜你喜欢
        • 2016-03-11
        • 2012-01-20
        • 2014-06-17
        • 2015-12-30
        • 2017-07-22
        • 2020-08-20
        • 1970-01-01
        • 2016-03-24
        相关资源
        最近更新 更多