zoukankan      html  css  js  c++  java
  • 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 ;
  • 相关阅读:
    [Linux]yum开启rpm包缓存
    [Linux]centOS7-1-1503-x86_64下安装VM-TOOLS
    [Linux]centOS7下RPM安装Perl
    vue 之 pageage.json 和 webpack.config.js
    node 之 apache
    node 之 express
    node 之 基础知识
    npm nvm nrm的关系
    echarts 学习笔记
    git 操作学习
  • 原文地址:https://www.cnblogs.com/beceo/p/2406025.html
Copyright © 2011-2022 走看看