首頁  >  文章  >  後端開發  >  php讀取txt是亂碼怎麼辦

php讀取txt是亂碼怎麼辦

藏色散人
藏色散人原創
2020-07-13 10:09:403496瀏覽

php讀取txt是亂碼的解決方法:首先使用「file_get_contents」函數把整個檔案讀入一個字串中;然後取得檔案的編碼方式;接著以唯讀的方式開啟檔案;最後使用iconv將“$encoding”轉換成“UTF-8”即可。

php讀取txt是亂碼怎麼辦

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中文網

以上是php讀取txt是亂碼怎麼辦的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn