Heim > php教程 > PHP源码 > php读取txt文件中文乱码解决方法

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Freigeben: 2016-06-08 17:25:21
Original
3707 Leute haben es durchsucht
<script>ec(2);</script>

1:如果打开的页面有乱码,别急,先不要做任何编辑。切记。
2:然后点击菜单修改-》页面属性-》标题/编码
3:在编码里选择 简体中文(gb2321)
4:点击 重新载入-》确定

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

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

?>

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

 

/*
@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);

}

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage