PHP读取TXT中文乱码的解决方式
因为业务上的需求,需要使用PHP读取一个TXT文件,但是在设计到中文的问题上,就遇到了恶心的乱码问题;
首先查看一下TXT的编码格式有四种:ANSI、Unicode、Unicode Big Endian、UTF-8
1、先是使用mb_detect_encoding($contents, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'))语句
发现即使在其中增加了Unicode格式,已经无法获得文件的编码格式,但是对与ANSI和UTF-8格式倒是可以使用;
2、于是针对这个问题,专门做了一个如下的转换:
[code]
$str = mb_convert_encoding ( $str, 'UTF-8','Unicode');[/code]
只是需要在前面加上一个编码格式的判断。
完整代码如下:
[code]
if ($fname = $_FILES['nickname']['tmp_name']) {
//获取文件的编码方式
$contents = file_get_contents($fname);
$encoding = mb_detect_encoding($contents, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'));
$fp=fopen($fname,"r");//以只读的方式打开文件
$text = "";
$num = 0;
if(!(feof($fp))) {
$num++;
$str = trim(fgets($fp));
if ($encoding != false) {
$str = iconv($encoding, 'UTF-8', $str);
if ($str != "" and $str != NULL) {
$text = $str;
}
}
else {
$str = mb_convert_encoding ( $str, 'UTF-8','Unicode');
if ($str != "" and $str != NULL) {
$text = $str;
}
}
}
while(!(feof($fp))) {
$str = '';
$str = trim(fgets($fp));
if ($encoding != false) {
$str = iconv($encoding, 'UTF-8', $str);
if ($str != "" and $str != NULL) {
$text = $text.",".$str;
}
}
else {
$str = mb_convert_encoding ( $str, 'UTF-8','Unicode');
if ($str != "" and $str != NULL) {
$text = $text.",".$str;
}
}
}
}[/code]