php中读文件中时,汉字乱码怎么解决

发布网友 发布时间:2022-04-06 06:33

我来回答

2个回答

懂视网 时间:2022-04-06 10:54

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

代码如下:

 //$fname文件名称
 if ($fname = $_FILES['nickname']['tmp_name']) {
 
  //file_get_contents() 函数把整个文件读入一个字符串中。
  $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) {
  //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.",".$str;
   }
  }
  else {
   $str = mb_convert_encoding ( $str, 'UTF-8','Unicode');
   if ($str != "" and $str != NULL) {
   $text = $text.",".$str;
   }
  }
  }
 }

更多相关知识,请访问PHP中文网!

热心网友 时间:2022-04-06 08:02

在<head>当中加上
<meta http-equiv=Content-Type content="text/html;charset=utf-8">

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com