Php--json_encode Chinese coding problem

Source: Internet
Author: User
Copyright NOTICE: This article is reproduced from the trace of memory (http://www.onmpw.com/tm/xwzj/prolan_122.html?

Hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io)

For reprint please contact the Cloud College team member Yin E-mail: yinhy#tingyun.com

In the PHP project will often encounter Chinese garbled, this is a more annoying problem. However, when the content needs to be exported to the Web page, we follow the following two principles generally will not appear in Chinese garbled.

The first is to add the HTML header

 
  

The 2nd is to ensure that the encoding of the file is consistent with the meta setting. In other words, if our first set of CharSet is UTF-8, then our file encoding will also be set to UTF-8. The two remain consistent.

Of course, the above is for the situation of the Web page, but now with Ajax in the Web application to occupy a larger proportion of the data in JSON format is more and more widely used in data transmission. Therefore, the use of Json_encode in PHP in the JSON conversion of data will also encounter Chinese garbled or is the problem of encoding Chinese.

As an example,

$data = array (' ID ' =>1, ' name ' + ' trace ' blog ', ' Parid ' =>0); Echo Json_encode ($data);

The output of the above code is

{"id": 1, "name": "\u8ff9\u5fc6\u535a\u5ba2", "Parid": 0}

We see that the function of the Chinese ' track-and-Trace blog ' has been 16 binary transcoding. This can not be said to be wrong, because 16 binary means the correct Chinese, we get this result, in the front end through JS also can get the results we want. But it's still a bit cumbersome to use. Of course, the situation will vary depending on the PHP version.

For some versions of PHP, the result would be the following scenario

{"id": 1, "name": null, "Parid": 0}

The Chinese cannot be parsed correctly.

There is no way, the Chinese problem is so troublesome. Who made computers not invented by Chinese? Of course, there are solutions to this, so let's look at two solutions.

First, by Json_encode the second parameter to solve

For the above problem, the php>=5.4.0 version can be solved directly by the Json_encode function itself. That's the second parameter plus json_unescaped_unicode.

$data = array (' ID ' =>1, ' name ' = ' Parid ', ' =>0 '); Echo Json_encode ($data, Json_unescaped_unicode);

Now we can get the right results.

{"id": 1, "name": "Trace Memory Blog", "Parid": 0}

The result is to get it right. However, the PHP version of the total can not be replaced by 5.4 and above the version of it. What should I do with a version below 5.4?

Second, solve the Chinese problem by URL coding

We know that there are two functions UrlEncode and UrlDecode in PHP. We can use the UrlEncode function to encode the Chinese URL so that there is no more Chinese in the string, and there is no problem with Chinese encoding.

$STR = "Trace Memory blog"; Echo UrlEncode ($STR);

URL encoding of the Trace memory blog, the results are as follows

%e8%bf%b9%e5%bf%86%e5%8d%9a%e5%ae%a2

So, we put the name of the above array after the value of UrlEncode encoding, and then the JSON format conversion, the Chinese encoding problem does not exist.

$data = array (' ID ' =>1, ' name ' =>urlencode (' Trace blog '), ' Parid ' =>0); $res = Json_encode ($data); Echo $res;

Now we get the result that the name code after the JSON string

{"id": 1, "name": "%e8%bf%b9%e5%bf%86%e5%8d%9a%e5%ae%a2", "Parid": 0}

Finally, the URL-encoded string is decoded by UrlDecode. Of course UrlDecode decoding does not need us to find the corresponding section of the encoded string to decode. We can URL decode the entire string directly. UrlDecode automatically detects the corresponding URL-encoded string to decode it.

$data = array (' ID ' =>1, ' name ' =>urlencode (' Trace blog '), ' Parid ' =>0); $res =urldecode (Json_encode ($data)); Echo $res ;

So the result is right.

{"id": 1, "name": "Trace Memory Blog", "Parid": 0}

There is no version limit to this approach, but the efficiency will certainly be slower than the first.

Encapsulation function for the second method--solving chinese problems by URL encoding

Now the problem is, for the second method, we can not always add the UrlEncode function in front of each text in the array. This is unrealistic, too. Then we can deal with this problem by encapsulating the Json_encode function ourselves.

The code is as follows

/** * Author: trace Memory * Personal blog: Trace Memory blog * Blog url:www.onmpw.com*/function onmpw_json_encode ($data) {        if (Is_object ($data)) return False ;        if (Is_array ($data)) {            $data = Deal_array ($data);        }        Return UrlDecode (Json_encode ($data));} function Deal_array ($data) {     if (Is_array ($data)) {        foreach ($data as $key = $val) {            if (Is_array ($val)) {                                     //If it is a multidimensional array, the multidimensional array is processed by recursion                $data [$key] = Deal_array ($val);            } else {                                     //URL-encode the value                $data [$key] = UrlEncode ($val);}}    ElseIf (is_string ($data)) {        $data = UrlEncode ($data);    }    return $data;}

Let's take a look at a usage example

$data = Array (            ' id ' =>1, ' name ' = ' Parid ', ' =>0 '),            array (' ID ' =>2, ' name ' = ' learning ', ' Parid ' =>1),            array (' ID ' =>3, ' name ' = ' Fun Talk ', ' Parid ' =>1),            array (' ID ' =>4, ' name ' = ' programming language ', ' Parid ' =>2),            array (' ID ' =>5, ' name ' = ' network ', ' Parid ' =>2),            array (' ID ' =>6, ' name ' = ' algorithm ', ' Parid ' =>2),            array (' ID ' =>7, ' name ' = ' operating system ', ' Parid ' =>2),            array (' ID ' =>8, ' name ' = ' database ', ' Parid ' =>2),            array (' ID ' =>9, ' name ' = ' web front ', ' Parid ' =>2),            array (' ID ' =>10, ' name ' = ' read ', ' Parid ' =>3),            array (' ID ' =>11, ' name ' = ' views and impressions ', ' Parid ' =>3)        ); $data = Onmpw_json_encode ($data); Echo $data;

Now we have the results we want.

[{"id": "1", "Name": "Trace Memory Blog", "Parid": "0"},{"id": "2", "Name": "Lifelong Learning", "Parid": "1"},{"id": "3", "Name": "Fun Talk", "Parid": "1" },{"id": "4", "Name": "Programming Language", "Parid": "2"},{"id": "5", "Name": "Network", "Parid": "2"},{"id": "6", "Name": "Algorithm", "Parid": "2"},{ "id": "7", "Name": "Operating System", "Parid": "2"},{"id": "8", "Name": "Database", "Parid": "2"},{"id": "9", "Name": "Web Front End", "Parid": "2"}, {"id": "Ten", "name": "Reading", "Parid": "3"},{"id": "One", "name": "Views and feelings", "Parid": "3"}]

Summarize

The problem of Chinese coding is very common, we should all summarize in the actual situation. In the future development of similar problems encountered can be easily solved.

For the above custom Json_encode function, I will encapsulate it in a public class. Source code is on GitHub, I will continue to encapsulate some of the common functions in this public class, welcome to click to download. I hope that this will be helpful to everyone.

To read more technical articles, visit the Cloud Technology blog and visit the official cloud website to learn more about the magic of application performance optimization.

  • 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.