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

发布于 2024-08-16 20:12:42 字数 215 浏览 4 评论 0原文

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

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

I need to create a loop through all files in subdirectories. Can you please help me struct my code like this:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

胡渣熟男 2024-08-23 20:12:42

RecursiveDirectoryIterator 与 RecursiveIteratorIterator 结合使用。

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

Use RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator.

$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
半﹌身腐败 2024-08-23 20:12:42

您需要将路径添加到递归调用中。

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 '  Found File or .-dir '.$item.'<br>';
    }
  }
}

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

readDirs($path);

You need to add the path to your recursive call.

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 '  Found File or .-dir '.$item.'<br>';
    }
  }
}

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

readDirs($path);
执笔绘流年 2024-08-23 20:12:42

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

$main = "MainDirectory";

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

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

You probably want to use a recursive function for this, in case your sub directories have sub-sub directories

$main = "MainDirectory";

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

didn't test the code, but this should be close to what you want.

怪我闹别瞎闹 2024-08-23 20:12:42

我喜欢带有通配符的 glob

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

详细信息和更复杂的场景。< /a>

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

I like glob with it's wildcards :

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

Details and more complex scenarios.

But if You have a complex folders structure RecursiveDirectoryIterator is definitively the solution.

雪若未夕 2024-08-23 20:12:42

来吧,先自己尝试一下吧!

你需要什么:

scandir()
is_dir()

当然还有 foreach

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

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

Come on, first try it yourself!

What you'll need:

scandir()
is_dir()

and of course foreach

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

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

枕梦 2024-08-23 20:12:42

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

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

Another solution to read with sub-directories and sub-files (set correct foldername):

<?php
$path = realpath('samplefolder/yorfolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
        echo "$filename <br/>";
}
?>
感性不性感 2024-08-23 20:12:42

如果我们可以安全地消除任何名为 的项目,则对 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>";
    }
}

Minor modification on what John Marty posted, if we can safely eliminate any items that are named . or ..

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>";
    }
}
拥醉 2024-08-23 20:12:42
    <?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();
?>
    <?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();
?>
倾城月光淡如水﹏ 2024-08-23 20:12:42
$allFiles = [];
public function dirIterator($dirName)
{
    $whatsInsideDir = scandir($dirName);
    foreach ($whatsInsideDir as $fileOrDir) {
        if (is_dir($fileOrDir)) {
            dirIterator($fileOrDir);
        }
        $allFiles.push($fileOrDir);
    }

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

    return $allFiles;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文