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

2017-12-06编程教程
119

 //$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;
                  }
              }
          }
      }

The End
乱码问题

相关推荐

PHP读取TXT中文乱码的解决方式
因为业务上的需求,需要使用PHP读取一个TXT文件,但是在设计到中文的问题上,就遇到了恶心的乱码问题; 首先查看一下TXT的编码格式有四种:ANSI、Unicode、Unicode Big Endian、UTF-8 1、先是使用mb_detect_encoding($contents, array(GB2312,GBK,UTF-16,UCS...
2018-02-06 编程教程
166

php使用curl post 发送url 并解决中文乱码问题
这个问题困扰我几天了,发送的指定网址的url参数,中文总是乱码,指定网址是utf8编码的,我发送的也是utf8编码的。但是还是乱码,开始用的file_get_contents,后来换成curl并在php.ini中开启了php_curl,还是不行,有加了header终于解决。代码如下: $url =...
2016-09-08 编程教程
195

file_get_contents 输出乱码问题
我的页面是utf-8,file_get_contents的页面是gb2312,输出时中文乱码。 解决方法如下: ?php header(Content-Type:text/html;charset=utf-8); $keyworld=跟班网; $keyworld=iconv(utf-8,gb2312,$keyworld); $url = http://www.baidu.com/s?f=8wd=$keyworld;...
2016-09-08 编程教程
285

在PHP中PDO解决中文乱码问题的一些补充-PHPphp技巧
跟版素材网(www.genban.org)提供PHP,PDO,中文乱码,等网页设计素材资源,提供相关网页设计资源的教程和免费下载。跟版网,专业织梦网页设计模板资源站。。...
2016-04-09 编程教程
84