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;

                  }

              }

          }

      }

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM