登录
首页 >  文章 >  php教程

PHP递归遍历文件夹详解教程

时间:2025-12-08 09:35:46 352浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

小伙伴们有没有觉得学习文章很有意思?有意思就对了!今天就给大家带来《PHP递归遍历文件夹方法详解》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

使用RecursiveDirectoryIterator和RecursiveIteratorIterator类可高效递归遍历文件夹,代码清晰且健壮,适合大多数场景;手动递归函数适合需要精细控制的场景;结合pathinfo可过滤特定类型文件,如.php文件;推荐优先使用迭代器方式。

php递归遍历文件夹

要使用PHP递归遍历文件夹,最简单高效的方式是利用内置的RecursiveDirectoryIteratorRecursiveIteratorIterator类。这种方式无需手动写递归逻辑,代码更清晰、健壮。

使用迭代器递归遍历目录

这是推荐的方法,适合大多数场景:

$dir = '/path/to/your/folder';
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach ($iterator as $fileinfo) {
    $depth = $iterator->getDepth();
    $indent = str_repeat("  ", $depth);
    
    if ($fileinfo->isDir()) {
        echo "$indent[DIR] " . $fileinfo->getFilename() . "\n";
    } else {
        echo "$indent" . $fileinfo->getFilename() . " (size: " . $fileinfo->getSize() . " bytes)\n";
    }
}

手动实现递归函数

如果你希望完全控制流程,也可以手动写递归函数:

function scanDirRecursively($path) {
    if (!is_dir($path)) {
        return;
    }

    $items = scandir($path);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }

        $fullPath = $path . DIRECTORY_SEPARATOR . $item;

        if (is_dir($fullPath)) {
            echo "[DIR] $fullPath\n";
            scanDirRecursively($fullPath); // 递归进入子目录
        } else {
            echo "FILE: $fullPath\n";
        }
    }
}

// 调用示例
scanDirRecursively('/path/to/your/folder');

只获取特定类型文件(如.php)

在实际项目中,你可能只想处理某种类型的文件。可以结合pathinfo()过滤:

$phpFiles = [];
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isFile()) continue;

    $ext = pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION);
    if ($ext === 'php') {
        $phpFiles[] = $fileinfo->getPathname();
    }
}

print_r($phpFiles);
提示: 使用迭代器方式性能更好,且能自动处理深层嵌套;手动递归更适合学习理解原理或需要特殊逻辑控制时使用。 基本上就这些。根据你的具体需求选择合适的方式即可。

终于介绍完啦!小伙伴们,这篇关于《PHP递归遍历文件夹详解教程》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>