首頁  >  文章  >  後端開發  >  解決php中文亂碼轉換問題

解決php中文亂碼轉換問題

藏色散人
藏色散人原創
2020-09-12 09:25:293466瀏覽

php中文亂碼轉換的解決方法:1、設定編碼為「header('Content-Type:text/html;charset=utf-8');」;2、使用「mb_convert_encoding」等函式進行轉換。

解決php中文亂碼轉換問題

推薦:《PHP影片教學

PHP程式碼中文輸出亂碼與轉碼問題

1.header('Content-Type:text/html;charset=utf-8'); 防止json格式的中文亂碼輸出,在輸出之前寫出此程式碼行

#2.字元轉碼:$a為待轉碼字串,$encode為$a的編碼規則,$to_encode 為$a 將要轉的編碼規則,$str_encode 轉碼後的字串,

(一): $encode = mb_detect_encoding($a, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));//获取当前字符串的编码
$str_encode = mb_convert_encoding($a, $to_encode, $encode);//将字符编码改为$to_encode
(二):$str_encode = iconv($encode, $to_encode, $a);//例:$A = iconv("gbk", "utf-8", $A);
(三):/**
 * 1.自动识别编码并转换为UTF-8
 */
function characet($data){
  if( !empty($data) ){   
    $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;  
    if( $fileType != 'UTF-8'){  
      $data = mb_convert_encoding($data ,'utf-8' , $fileType);  
    }  
  }  
  return $data;   
}

3.自己寫了一個小得處理PHP程式碼http偵錯時輸出漢字的程式碼:

//防止中文转码,遍历数据结果,每项单独urlencode,
    public function arrayUrlencode($array) {
        if (empty($array)) {
            return $array;
        } else {
            foreach ($array as $key =>$value) {//对每个数组元素进行urlencode
                if (is_array($value)) {
                    $array[$key] =$this->arrayUrlencode($value);
                } else {
                    $array[$key] =urlencode($value);
                }
            }
        }
        return $array;
    }
 
    //再整体urldecode
    public function arrayJsonencode($array) {
        $url_arr =$this->arrayUrlencode($array);
        $json_arr = json_encode($url_arr);//json 输出
        return urldecode($json_arr); //整体urldecode
}

以上是解決php中文亂碼轉換問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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