如何递归PHP目录当中的文件?

用老旧的文件和目录读取函数,已经过时了,一般用glob,高效直接。但是glob不能递归获取(或者说我没找到,所以有替代方法)

方法一:(推荐使用)SPL

Those of you with PHP 5 don't have to come up with these wild functions to scan a directory recursively: the SPL can do it.

<?php

$dir_iterator 
= new RecursiveDirectoryIterator("/path");
$iterator = new RecursiveIteratorIterator($dir_iteratorRecursiveIteratorIterator::SELF_FIRST);
// could use CHILD_FIRST if you so wish

foreach ($iterator as $file) {
    echo 
$file"\n";
}

?>

Not to mention the fact that $file will be an SplFileInfo class, so you can do powerful stuff really easily:

<?php

$size 
0;
foreach (
$iterator as $file) {
    if (
$file->isFile()) {
        echo 
substr($file->getPathname(), 27) . ": " $file->getSize() . " B; modified " date("Y-m-d"$file->getMTime()) . "\n";
        
$size += $file->getSize();
    }
}

echo 
"\nTotal file size: "$size" bytes\n";

?>

方法二:

if ( ! function_exists('glob_recursive'))
{
    
// Does not support flag GLOB_BRACE
    
    
function glob_recursive($pattern$flags 0)
    {
        
$files glob($pattern$flags);
        
        foreach (
glob(dirname($pattern).'/*'GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
        {
            
$files array_merge($filesglob_recursive($dir.'/'.basename($pattern), $flags));
        }
        
        return 
$files;
    }
}

来自文档:http://cn2.php.net/manual/en/function.glob.php

转载于:https://my.oschina.net/sefier/blog/98814

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值