php讀取txt是亂碼怎麼辦

2020-07-16 10:06:21

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

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是亂碼怎麼辦的詳細內容,更多請關注TW511.COM其它相關文章!