PHP 读取子目录并循环文件如何?

问题描述 投票:0回答:10

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

$main = "MainDirectory";
loop through sub-directories {
    loop through filels in each sub-directory {
        do something with each file
    }
};
php loops directory
10个回答
159
投票

RecursiveDirectoryIterator 与 RecursiveIteratorIterator 结合使用。

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

9
投票

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

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);

9
投票

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

$main = "MainDirectory";

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

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


5
投票

我喜欢

glob
及其通配符 :

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

细节和更复杂的场景。

但是如果您有复杂的文件夹结构

RecursiveDirectoryIterator
绝对是解决方案。


4
投票

来吧,先自己尝试一下!

您需要什么:

scandir()
is_dir()

当然还有

foreach

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

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


3
投票

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

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

2
投票

如果我们可以安全地消除任何名为 的项目,则对 John Marty 发布的内容进行小修改。或..

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>";
    }
}

1
投票
    <?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();
?>

1
投票
$allFiles = [];
public function dirIterator($dirName)
{
    $whatsInsideDir = scandir($dirName);
    foreach ($whatsInsideDir as $fileOrDir) {
        if (is_dir($fileOrDir)) {
            dirIterator($fileOrDir);
        }
        $allFiles.push($fileOrDir);
    }

    return $allFiles;
}

0
投票

[1]:https://stackoverflow.com/users/2169/micha%C5%82-nied%C5%BAwiedzki。这个解决方案有错误。我认为重命名后未找到 $file。需要设置 $size = $file->getSize() 才能重新命名。这个解决方案是最好的!

© www.soinside.com 2019 - 2024. All rights reserved.