Analysis of json_encode Chinese Encoding Problems in php

Source: Internet
Author: User

For example, if 'signature' is changed to '\ u80e5' after json_encode processing, the Chinese part of the final json is replaced with unicode encoding. What we need to solve is to convert the object to json and ensure that the Chinese character inside the object still appears in json as normal Chinese. Now it seems that json_encode alone cannot achieve the goal.
My solution: perform url encoding for the Chinese fields in the class first, then perform json encoding (jsonencode) for the object, and finally url Decoding (urldecode) json, that is, the final json. The Chinese in it is still the Chinese!
The test code is as follows:
Copy codeThe Code is as follows:
<? Php
Class myClass {
Public $ item1 = 1;
Public $ item2 = 'Chinese ';
Function to_json (){
// Url encoding to avoid converting Chinese to unicode using json_encode
$ This-> item2 = urlencode ($ this-> item2 );
$ Str_json = json_encode ($ this );
// Url Decoding. After converting json, all attributes are returned, so that the object attributes remain unchanged.
$ This-> item2 = urldecode ($ this-> item2 );
Return urldecode ($ str_json );
}
}
$ C = new myClass ();
Echo json_encode ($ c );
Echo '<br/> ';
Echo $ c-> to_json ();
Echo '<br/> ';
Echo json_encode ($ c );
Echo '<br/> ';
Echo json_encode ('authorization ');
?>

Program output result:
Copy codeThe Code is as follows:
{"Item1": 1, "item2": "\ u4e2d \ u6587 "}
{"Item1": 1, "item2": "Chinese "}
{"Item1": 1, "item2": "\ u4e2d \ u6587 "}
"\ U80e5"

I hope this article will serve as a reference to collect better solutions ......!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.