php 获取某个文件夹及其子文件夹的所有文件并支持文件格式的筛选

1年前之前写过一个批量将文件转化成utf-8编码的函数,最近想用,却找不到了,今天重新了个获取某文件夹下所有文件的方法,且做记录,供以后使用。

<?php 
//php 获取某个文件夹及其子文件夹的所有文件并支持文件格式的筛选
function getAllFiles($folder, &$fileList=array(), $fileType=array()) {
    $folder = empty($folder) ? dirname(__FILE__) : $folder;    
    $folder = str_replace('\\','/',$folder);
    $fileList = empty($fileList) ? array() : $fileList;
    $d = dir($folder);
    while (false !== ($file = $d->read())) {
       if($file != '.' && $file != '..') {
            $f = $folder.'/'.$file;
            if(is_dir($f)) {
                getAllFiles($f, $fileList ,$fileType);
            } else {
                if(!empty($fileType)) {
                    if(in_array(pathinfo($f, PATHINFO_EXTENSION), $fileType)) {
                        $fileList[] =  $f;
                    }
                } else {
                    $fileList[] =  $f;
                }
            }
       }
    }
    $d->close(); 
}

//转换到期望的编码格式
function convertFileCharset($files, $inCharset='', $outCharset='') {
    foreach($files as $file) {
        $contents = file_get_contents($file);
        $inCharset = mb_detect_encoding($contents) === false ? $inCharset : mb_detect_encoding($contents);
        $outCharset = empty($outCharset) ? $inCharset : $outCharset;
        if(!empty($contents)) {
            $contents = iconv($inCharset, $outCharset.'//ignore', $contents);
            file_put_contents($file,$contents);
        }
    }
}

$t1 = microtime(true);
$folder = dirname(__FILE__).'/develop';
$fileList = array();
getAllFiles($folder, $fileList, array('php','htm','css','js'));
//echo '<pre>';print_r($fileList);exit;
convertFileCharset($fileList, 'GBK', 'UTF-8');
$t2 = microtime(true);
echo $t2 - $t1 ;

 

转载于:https://www.cnblogs.com/beceo/archive/2012/03/19/2406025.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值