php检测文件编码的方法_PHP教程

WBOY
Release: 2016-07-13 10:31:49
Original
832 people have browsed it

关于文件编码的检测,百度一下一大把都是,但是确实没有能用的、很多人建议 mb_detect_encoding 检测,可是不知为何我这不成功,什么都没输出、看到有人写了个增强版,用 BOM 判断的,我果断就无视了,这东西完全不靠谱、最终根据PHP手册里 mb_detect_encoding 函数下方的例子,自己写了一个检测函数,

还包括自动检测编码并按指点编码读取文件的函数、源码献上。

复制代码 代码如下:

/**

* 检测文件编码

* @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 "";

}

www.bkjia.com true http://www.bkjia.com/PHPjc/761297.html TechArticle 关于文件编码的检测,百度一下一大把都是,但是确实没有能用的、很多人建议 mb_detect_encoding 检测,可是不知为何我这不成功,什么都没...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!