1 <?php
2 /**
3 * 检测文件编码
4 * @param string $file 文件路径
5 * @return string|null 返回 编码名 或 null
6 */
7 function detect_encoding($file) {
8 $list = array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1');
9 $str = file_get_contents($file);
10 foreach ($list as $item) {
11 $tmp = mb_convert_encoding($str, $item, $item);
12 if (md5($tmp) == md5($str)) {
13 return $item;
14 }
15 }
16 return null;
17 }
18
19 /**
20 * 自动解析编码读入文件
21 * @param string $file 文件路径
22 * @param string $charset 读取编码
23 * @return string 返回读取内容
24 */
25 function auto_read($file, $charset='UTF-8') {
26 $list = array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1');
27 $str = file_get_contents($file);
28 foreach ($list as $item) {
29 $tmp = mb_convert_encoding($str, $item, $item);
30 if (md5($tmp) == md5($str)) {
31 return mb_convert_encoding($str, $charset, $item);
32 }
33 }
34 return "";
35 }