【问题标题】:PHP read sub-directories and loop through files how to?PHP如何读取子目录和循环文件?
【发布时间】:2011-01-02 03:17:05
【问题描述】:

我需要创建一个循环遍历子目录中的所有文件。你能帮我这样构造我的代码吗:

$main = "MainDirectory";
loop through sub-directories {
    loop through filels in each sub-directory {
        do something with each file
    }
};

【问题讨论】:

标签: php loops directory


【解决方案1】:

RecursiveDirectoryIterator 与 RecursiveIteratorIterator 结合使用。

$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}

【讨论】:

  • 如果它对任何人都有用,上面的$fileSplFileInfo 的一个实例,以及随之而来的方法(getBasename、getSize 等) - 花了我一点时间同时弄清楚这一点。
  • @NickF 是的,很高兴知道! $file-&gt;isDir$file-&gt;isDot也很有用。
【解决方案2】:

您需要添加递归调用的路径。

function readDirs($path){
  $dirHandle = opendir($path);
  while($item = readdir($dirHandle)) {
    $newPath = $path."/".$item;
    if(is_dir($newPath) && $item != '.' && $item != '..') {
       echo "Found Folder $newPath<br>";
       readDirs($newPath);
    }
    else{
      echo '&nbsp;&nbsp;Found File or .-dir '.$item.'<br>';
    }
  }
}

$path =  "/";
echo "$path<br>";

readDirs($path);

【讨论】:

    【解决方案3】:

    您可能希望为此使用递归函数,以防您的子目录有子子目录

    $main = "MainDirectory";
    
    function readDirs($main){
      $dirHandle = opendir($main);
      while($file = readdir($dirHandle)){
        if(is_dir($main . $file) && $file != '.' && $file != '..'){
           readDirs($file);
        }
        else{
          //do stuff
        }
      } 
    }
    

    没有测试代码,但这应该接近你想要的。

    【讨论】:

    • 它将陷入无限循环尝试递归读取目录“。” (单点 - 当前目录)。你需要修改你的 if 语句: if (is_dir($file) and $file != '.')
    • 谢谢,我忘记了,将其添加到代码中。很高兴我提出了未经测试的免责声明:)
    • 缺少右括号while($file = readdir($dirHandle){,否则完美!谢谢。
    • 这种方法在您需要文件路径和文件名的情况下变得困难
    • 这种方法行不通。 is_dir($file) 不检查 $file 是否为目录。 is_dir 采用绝对路径...而 $file 只是一个子文件夹...
    【解决方案4】:

    我喜欢带有通配符的glob

    foreach (glob("*/*.txt") as $filename) {
        echo "$filename\n";
    }
    

    Details and more complex scenarios.

    但如果您的文件夹结构复杂,RecursiveDirectoryIterator 绝对是解决方案。

    【讨论】:

    • 短小甜甜。建议将“\n”(写入 txt 文件时的换行符)替换为“
      ”(HTML 换行符)。
    • 关于通配符的好主意!没想到。
    【解决方案5】:

    来吧,先自己试试吧!

    你需要什么:

    scandir()
    is_dir()
    

    当然还有foreach

    http://php.net/manual/en/function.is-dir.php

    http://php.net/manual/en/function.scandir.php

    【讨论】:

    • 如果您要链接到文档的德语版本,请至少用德语回答问题。
    • @erier 我的错,修复了链接。
    【解决方案6】:

    另一种解决方案读取子目录和子文件(设置正确的文件夹名称):

    <?php
    $path = realpath('samplefolder/yorfolder');
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
    {
            echo "$filename <br/>";
    }
    ?>
    

    【讨论】:

      【解决方案7】:

      如果我们可以安全地删除任何名为 .或..

      function readDirs($path){
        $dirHandle = opendir($path);
        while($item = readdir($dirHandle)) {
          $newPath = $path."/".$item;
          if (($item == '.') || ($item == '..')) {
              continue;
          }
          if (is_dir($newPath)) {
              pretty_echo('Found Folder '.$newPath);
              readDirs($newPath);
          } else {
              pretty_echo('Found File: '.$item);
          }
        }
      }
      
      function pretty_echo($text = '')
      {
          echo $text;
          if (PHP_OS == 'Linux') {
              echo "\r\n";
          }
          else {
              echo "</br>";
          }
      }
      

      【讨论】:

        【解决方案8】:
            <?php
            ini_set('max_execution_time', 300);  // increase the execution time of the file (in     case the number of files or file size is more).
            class renameNewFile {
        
            static function copyToNewFolder() {  // copies the file from one location to another.
                $main = 'C:\xampp\htdocs\practice\demo';  // Source folder (inside this folder subfolders and inside each subfolder files are present.)
                $main1 = 'C:\xampp\htdocs\practice\demomainfolder'; // Destination Folder
                $dirHandle = opendir($main); // Open the source folder
                while ($file = readdir($dirHandle)) { // Read what's there inside the source folder
                    if (basename($file) != '.' && basename($file) != '..') {   // Ignore if the folder name is '.' or '..' 
                        $folderhandle = opendir($main . '\\' . $file);   // Open the Sub Folders inside the Main Folder
                        while ($text = readdir($folderhandle)) {
                            if (basename($text) != '.' && basename($text) != '..') {     //  Ignore if the folder name is '.' or '..'
                                $filepath = $main . '\\' . $file . '\\' . $text;
                                if (!copy($filepath, $main1 . '\\' . $text))           // Copy the files present inside the subfolders to destination folder
                                    echo "Copy failed";
                                else {
                                    $fh = fopen($main1 . '\\' . 'log.txt', 'a');     // Write a log file to show the details of files copied.
                                    $text1 = str_replace(' ', '_', $text);
                                    $data = $file . ',' . strtolower($text1) . "\r\n";
                                    fwrite($fh, $data);
                                    echo $text . " is copied <br>";
                                }
                            }
                        }
                    }
                }
            }
        
            static function renameNewFileInFolder() {                //Renames the files into desired name
                $main1 = 'C:\xampp\htdocs\practice\demomainfolder';
                $dirHandle = opendir($main1);
        
                while ($file = readdir($dirHandle)) {
                    if (basename($file) != '.' && basename($file) != '..') {
                        $filepath = $main1 . '\\' . $file;
                        $text1 = strtolower($filepath);
                        rename($filepath, $text1);
                        $text2 = str_replace(' ', '_', $text1);
                        if (rename($filepath, $text2))
                            echo $filepath . " is renamed to " . $text2 . '<br/>';
                    }
                }
            }
        
        }
                renameNewFile::copyToNewFolder();
                renameNewFile::renameNewFileInFolder();
        ?>
        

        【讨论】:

          【解决方案9】:
          $allFiles = [];
          public function dirIterator($dirName)
          {
              $whatsInsideDir = scandir($dirName);
              foreach ($whatsInsideDir as $fileOrDir) {
                  if (is_dir($fileOrDir)) {
                      dirIterator($fileOrDir);
                  }
                  $allFiles.push($fileOrDir);
              }
          
              return $allFiles;
          }
          

          【讨论】:

            猜你喜欢
            • 2012-03-11
            • 1970-01-01
            • 2016-03-11
            • 2014-11-10
            • 1970-01-01
            • 1970-01-01
            • 2015-02-19
            • 2019-08-12
            • 2017-10-08
            相关资源
            最近更新 更多