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

Posted 一生不过烟花

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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读取TXT中文乱码的解决方法的主要内容,如果未能解决你的问题,请参考以下文章

怎么解决读取txt文件读取时中文乱码问题

iOS-读取txt文件中文乱码

c#读取到的TXT文件中的中文乱码怎么解决

Sublime Text 3读取txt文件乱码

java 逐行读取txt文本如何解决中文乱码

解决FileInputStream 读取文件中文乱码问题(转)