PHP批量转换文件编码为utf-8 不指定

jed , 2018-3-14 09:26 , 代码编程 , 评论(0) , 阅读(1409) , Via 本站原创 | |

使用时向 read_dir 函数传入路径和要转换到的编码, 默认utf-8

比如传入这个路径,则函数会将WWW文件夹下所有的编码转换为utf-8:
read_dir("D:\WEB\phpStudy\PHPTutorial\WWW");



<?php
//传入要转码的路径
$data = read_dir("C:\WEB\phpStudy\PHPTutorial\WWW\youjia");
debug($data);

//遍历方式
function read_dir($dir = '', $charset_to = 'utf-8')
{
    $files = array();
    $dir_list = scandir($dir);

    if (empty($dir_list)) return $files;

    //跳过的目录
    $not_dir = array('..', '.', '.idea', '.svn');
    //跳过的文件后缀
    $not_file = array('gif', 'png', 'jpg', 'db', 'dll', 'swf', 'ttf', 'psd', 'ico', 'url');
    $extension = array();
    foreach ($dir_list as $key => $file) {
        if (!in_array($file, $not_dir)) {
            $path = $dir . '/' . $file;
            if (is_dir($path)) {
                $files[$file] = read_dir($path);
            } else {
                $_file = pathinfo($file);

                if (isset($_file['extension']) && !in_array($_file['extension'], $not_file)) {
                    //获取原文件编码
                    $charset = strtolower(@detect_encoding($file));
                    if ($charset != $charset_to) {
                        //读取文件内容
                        $get_file = file_get_contents($path);
                        //编码转换为utf-8
                        $iconv = iconv("{$charset}//IGNORE", $charset_to, $get_file);
                        //将转换后的utf-8编码写入文件
                        file_put_contents($path, $iconv);
                    }
                }

                $files[] = $file;
            }
        }
    }

    return $files;
}

/**
* 检测文件编码
* @param string $file 文件路径
* @return string|null 返回 编码名 或 null
*/
function detect_encoding($file)
{
    $list = array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1');
    $str = @file_get_contents($file);
    foreach ($list as $item) {
        $tmp = @mb_convert_encoding($str, $item, $item);
        if (md5($tmp) == md5($str)) {
            return $item;
        }
    }
    return null;
}

//简单打印函数
function debug($str)
{
    echo "<pre>";
    if (is_array($str)) {
        print_r($str);
    } else {
        var_dump($str);
    }
    exit;
}
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]