首页 > php文件操作 > php读取txt文件中文乱码解决方法

php读取txt文件中文乱码解决方法

1:如果打开的页面有乱码,别急,先不要做任何编辑,切记

2:然后点击菜单修改-》页面属性-》标题/编码

3:在编码里选择 简体中文(gb2321)

4:点击 重新载入-》确定

新建一个记事本,不是写字板,然后将那个要读取的文件全部复制到这个记事本文件中,保存,再用如下代码读取那个记事本文件1303275.txt,发现当网页编码为gb2312时全部正常显示,改为utf8编码后,数字正常,汉字为乱码,这也属于正常.

<?php
$file = fopen("1303275.txt", "r"); //只读方式打开文本文件
while (!feof($file)) //当文件不结束
{
    $line = fgets($file); //读一行到$line变量
    echo $line . "<br />";
}
fclose($file); //关闭文本文件
?>

上面的方法比较笨但也解决问题,下面我提供一个不管什么txt文本都不会乱的解决方法,代码如下:

<?php
/*
@params $str 输入字符 $type 所需获取编码 
@author 长行 
*/
function autoiconv($str, $type = "gb2312//ignore") {
    $utf32_big_endian_bom = chr(0x00) . chr(0x00) . chr(0xfe) . chr(0xff);
    $utf32_little_endian_bom = chr(0xff) . chr(0xfe) . chr(0x00) . chr(0x00);
    $utf16_big_endian_bom = chr(0xfe) . chr(0xff);
    $utf16_little_endian_bom = chr(0xff) . chr(0xfe);
    $utf8_bom = chr(0xef) . chr(0xbb) . chr(0xbf);
    $first2 = substr($str, 0, 2);
    $first3 = substr($str, 0, 3);
    $first4 = substr($str, 0, 3);
    if ($first3 == $utf8_bom) $icon = 'utf-8';
    elseif ($first4 == $utf32_big_endian_bom) $icon = 'utf-32be';
    elseif ($first4 == $utf32_little_endian_bom) $icon = 'utf-32le';
    elseif ($first2 == $utf16_big_endian_bom) $icon = 'utf-16be';
    elseif ($first2 == $utf16_little_endian_bom) $icon = 'utf-16le';
    else {
        $icon = 'ascii';
        return $str;
    }
    return iconv($icon, $type, $str);
}
?>


本文地址:http://www.phprm.com/wenjian/fs4172.html

转载随意,但请附上文章地址:-)

标签:php读取txt 文件中文乱码

发表留言