您的位置:首页 > 编程语言 > PHP开发

PHP读取TXT中文乱码的解决方式

2015-12-14 20:35 609 查看
因为业务上的需求,需要使用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、于是针对这个问题,专门做了一个如下的转换:

$str = mb_convert_encoding ( $str, 'UTF-8','Unicode');

只是需要在前面加上一个编码格式的判断。

完整代码如下:

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;

}

}

}

}

注:本文转载自http://my.oschina.net/landry17h/blog/17145
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: