php中mb_detect_encoding检测文件编码方法[非完美]
关于文件编码的检测,百度一下一大把都是,但是确实没有能用的、
很多人建议 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.jiaochengji.com 。
2.encoding_list:encoding_list 是一个字符编码列表。 编码顺序可以由数组或者逗号分隔的列表字符串指定。
如果省略了 encoding_list 将会使用 detect_order。
3.strict:strict 指定了是否严格地检测编码。 默认是 FALSE。
下面举个例子:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy4421')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy4421>$encode = mb_detect_encoding($keytitle,array('ASCII','GB2312','GBK','UTF-8'));
三个参数分别是:被检测的输入变量.编码方式的检测顺序(一旦为真,后面自动忽略).
strict模式对编码检测的顺序进行调整,将最大可能性放在前面,这样减少被错误转换的机会.
一般要先排gb2312,当有GBK和UTF-8时,需要将常用的排列到前面
完整实例
<?php
/**
* 检测文件编码
* @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()函数
您可能感兴趣的文章:
php中mb_detect_encoding检测文件编码方法[非完美]
php 检测字符编码mb_detect_encoding()函数
php获取字符串编码的函数mb_detect_encoding
php mb_detect_encoding检测字符串编码有误的问题
php检测文件编码的方法示例
php判断字符编码的二个方法
php 自动检测内容编码并转换的代码
php判断字符串编码是否为utf8的函数举例
php获取字符串的编码格式的函数
学习php字符串编码的转换与判断