• 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 ;
  • 相关阅读:
    .java中如何实现序列化,有什么意义
    缓存穿透
    缓存击穿
    缓存雪崩
    redis缓存预热
    Docket 的常用命令
    数据库优化方法
    servlet和jsp的区别:
    6原则1法则
    学习IntelliJ IDEA(二)模块
  • 原文地址:https://www.cnblogs.com/beceo/p/2406025.html
Copyright © 2020-2023  润新知