由于业务上的需求,须要使用PHP读取一个TXT文件,可是在设计到中文的问题上,就遇到了恶心的乱码问题;web
首先查看一下TXT的编码格式有四种:ANSI、Unicode、Unicode Big Endian、UTF-8编码
一、先是使用mb_detect_encoding($contents, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'))语句spa
发现即便在其中增长了Unicode格式,已经没法得到文件的编码格式,可是对与ANSI和UTF-8格式却是能够使用;设计
二、因而针对这个问题,专门作了一个以下的转换:code
$str = mb_convert_encoding ( $str, 'UTF-8','Unicode');orm
只是须要在前面加上一个编码格式的判断。ci
完整代码以下:get
if ($fname = $_FILES['nickname']['tmp_name']) {it
//获取文件的编码方式class
$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;
}
}
}
}