Home>Article>Backend Development> Solve the problem of php Chinese garbled code conversion
Solution to php Chinese garbled code conversion: 1. Set the encoding to "header('Content-Type: text/html; charset=utf-8');"; 2. Use functions such as "mb_convert_encoding" to perform Convert.
Recommended: "PHP Video Tutorial"
PHP code Chinese output garbled code and transcoding issues
1.header('Content-Type:text/html;charset=utf-8'); To prevent Chinese garbled output in json format, write this line of code before output
2. Character transcoding: $a is the string to be transcoded, $encode is the encoding rule of $a, $to_encode is the encoding rule that $a will be converted to, $str_encode is the transcoded string,
(一): $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. I wrote a small code that handles PHP code and outputs Chinese characters during http debugging:
//防止中文转码,遍历数据结果,每项单独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 }
The above is the detailed content of Solve the problem of php Chinese garbled code conversion. For more information, please follow other related articles on the PHP Chinese website!