今天需要做一个txt协议内容直接上传转换文本显示的功能,用php直接读取内容后发现乱码了,完全看不懂。
经过寻找经验,发现了一个比较好的处理方法:
<?php
function read_txt($fileName)
{
$contents = file_get_contents($fileName);
//获取文件的编码方式
$encoding = mb_detect_encoding($contents, array('GB2312', 'GBK', 'UTF-16', 'UCS-2', 'UTF-8', 'BIG5', 'ASCII'));
$fp = fopen($fileName, "r");//以只读的方式打开文件
$text = "<div>";
$num = 0;
if (!(feof($fp))) {
$num++;
$str = trim(fgets($fp));
if ($encoding != false) {
//iconv ()将$encoding 转换成“UTF-8”
$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 . "<br>" . $str;
}
} else {
$str = mb_convert_encoding($str, 'UTF-8', 'Unicode');
if ($str != "" and $str != NULL) {
$text = $text . "<br>" . $str;
}
}
}
$text .= '</div>';
return $text;
}
read_txt(__DIR__ . '/xieyi.txt');
效果图如下: