Solution to json_encode in php to deal with gbk and gb2312 Chinese garbled problems
This article describes how json_encode in php handles the Chinese garbled problem of gbk and gb2312. The specific method is as follows:
1.json_encode() Chinese returns null for Chinese in gbk/gb2312
$arr = array ( array ( 'catid' => '4', 'catname' => 'www.jb51.net', 'meta_title' => '脚本之家' ) ); echo json_encode($arr);
Run result:
[{"catid":"4","catname":"www.jb51.net","meta_title":null}]
Have you taken a look? "meta_title":null He originally had One value is "Script Home". We checked and the principle is that json_encode only supports uft-8 encoding. Let's convert it
<?php $data="JSON中文"; $newData=iconv("GB2312″,"UTF-8//IGNORE",$data); echo $newData; //ignore的意思是忽略转换时的错误,如果没有ignore参数,所有该字符后面的字符都不会被保存。 //或是("GB2312″,"UTF-8″,$data); ?>
2. The background PHP page (the page is encoded as UTF-8 or the characters have been converted to UTF-8) uses json_encode to convert the array array in PHP into a JSON string. For example:
<?php $testJSON=array('name'=>'中文字符串','value'=>'test'); echo json_encode($testJSON); ?>
View the output result as:
{"name":"u4e2du6587u5b57u7b26u4e32″,"value":"test"}
It can be seen that UTF8 encoding is used characters, Chinese garbled characters also appear when using json_encode. The solution is to process the characters with the function urlencode() before using json_encode, then json_encode, and then use the function urldecode() to convert them back when outputting the result. The details are as follows:
<?php $testJSON=array('name'=>'中文字符串','value'=>'test'); //echo json_encode($testJSON); foreach ( $testJSON as $key => $value ) { $testJSON[$key] = urlencode ( $value ); } echo urldecode ( json_encode ( $testJSON ) ); ?>
View the output result:
{"name":"中文字符串","value":"test"}
Summary: json_encode function It can only process uft8 strings. If it is Chinese, it probably does not handle bytes well, because the lengths of Chinese gbk and uft are different. This will not be introduced in depth.
For more related articles on how json_encode in PHP handles gbk and gb2312 Chinese garbled problems, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment