Use the PHPjson_encode function to convert Chinese characters. What we will bring to you today is the solution to the problem that occurs when the PHPjson_encode function is processing the Chinese conversion. Json is a good data structure and is now widely used on the internet. what we will bring to you today is the solution to the problem that occurs when the PHP json_encode function handles Chinese conversion. Json is a good data structure and is now widely used in network data transmission,
Json_encode and json_decode
There are many related articles on the Internet about the specific usage of these two functions. This article mainly introduces the solution for converting Chinese characters when using json_encode. This article assumes that the file is encoded as gb2312;
Write out the required array first
- <? PHP
- $ Json = array (
- 0 =>
- Array (
- 'Id' =>'13 ',
- 'Name' =>'Table tennis ',
- ),
- 1 =>
- Array (
- 'Id' =>'17 ',
- 'Name' =>'Basketball ',
- )
- )
- ?>
If you directly use the PHP json_encode function
- < ?PHP
- echo json_encode($json);
- ?>
-
Result:
- < ?PHP
- [{"id":"13","name":null}
,{"id":"13","name":null}]
- ?>
-
We can see that the Chinese characters are not escaped as null because json only escapes the encoding, so the preceding statement should first convert the encoding.
- < ?PHP
- foreach ($ajax as $key=>$val)
- {
- $ajax[$key]['name'] =
urlencode($val['name']);
- }
- echo json_encode($json);
- ?>
Client js code
- < script type="text/javascript">
- function getsort(obj)
- {
- $.ajax(
- {
- type : "GET",
- url : "< ?=$this->baseUrl?>/index/getajax",
- data : "c=" obj.value,
- success : function(json)
- {
- var json=eval(json);
- var html = '< select>';
- $.each(json, function(k)
- {
- html = '< option value="'
json[k]['id'] '">'
decodeURI(json[k]['name']) '< /option>';
- });
- html ="< /select>";
- $('#sort').html(html);
- }
- }
- )
- }
- < /script>
The above code js reports an error saying that the encoding does not conform to the standard.
The reason is that decodeURI in js only supports utf8 transcoding. Therefore, the code of the PHP json_encode function should be the following code:
- < ?PHP
- foreach ($ajax as $key=>$val)
- {
- $ajax[$key]['name'] =
urlencode(iconv('gb2312',
'utf-8',$val['name']));
- }
- echo json_encode($json);
- ?>
-
The above is how to solve the problem in actual operations using the PHP json_encode function.
The json_encode function solves the problem when processing the Chinese conversion. Json is a good data structure and is now widely used in the internet...