Heim > php教程 > PHP源码 > Hauptteil

php中mb_detect_encoding检测文件编码方法[非完美]

WBOY
Freigeben: 2016-06-08 17:22:49
Original
1154 Leute haben es durchsucht

在php中我们可以利用mb_detect_encoding函数来检查字符串编码或文件编码,mb_detect_encoding函数是php内置的一个函数了,下面我们简单介绍。

<script>ec(2);</script>

关于文件编码的检测,百度一下一大把都是,但是确实没有能用的、
很多人建议 mb_detect_encoding() 检测,可是不知为何我这不成功,什么都没输出、
看到有人写了个增强版,用 BOM 判断的,我果断就无视了,这东西完全不靠谱、
最终根据PHP手册里 mb_detect_encoding 函数下方的例子,自己写了一个检测函数,
还包括自动检测编码并按指点编码读取文件的函数、
源码献上,不喜勿喷。
网上的方法我试过没用才写的,说不定环境不一样导致的。
所以万一没用,也别喷我,我只是共享想思路而已、、

php手册是这样解释的:

mb_detect_encoding — 检测字符的编码,  string mb_detect_encoding ( string $str [, mixed $encoding_list = mb_detect_order() [, bool $strict = false ]] )

这个函数有三个参数 分别是:

1.str:待检查的字符串 www.111cn.net 。      

2.encoding_list:encoding_list 是一个字符编码列表。 编码顺序可以由数组或者逗号分隔的列表字符串指定。

如果省略了 encoding_list 将会使用 detect_order。      

3.strict:strict 指定了是否严格地检测编码。 默认是 FALSE。      

下面举个例子:

 代码如下 复制代码

$encode = mb_detect_encoding($keytitle,array('ASCII','GB2312','GBK','UTF-8'));

三个参数分别是:被检测的输入变量.编码方式的检测顺序(一旦为真,后面自动忽略).

strict模式对编码检测的顺序进行调整,将最大可能性放在前面,这样减少被错误转换的机会.

一般要先排gb2312,当有GBK和UTF-8时,需要将常用的排列到前面


完整实例

 代码如下 复制代码

/**
 * 检测文件编码
 * @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;
}

/**
 * 自动解析编码读入文件
 * @param string $file 文件路径
 * @param string $charset 读取编码
 * @return string 返回读取内容
 */
function auto_read($file, $charset='UTF-8') {
    $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 mb_convert_encoding($str, $charset, $item);
        }
    }
    return "";
}

最后推荐一篇php 检测字符编码mb_detect_encoding()函数

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!