Php functions to solve json Chinese garbled characters

Source: Internet
Author: User
Tags character set json php tutorial

The php Tutorial comes with json_encode to process json data, so they do not support Chinese. Let's take a look at the example below.

Echo json_encode (array (123213, 'China '));


{"Platformid": "123213", "userid": "1023", "username": "u00b7u00f0u00b5u00b2u00c9u00b1u00b7u00f0u00ccu00fc "}

We will find that the English language can be correctly parsed, but the Chinese language is u00b7u00f0u00b5u00b2u00c9u00b1u00b7u00f0u00ccu00fc. This may be unicode code, but I did not test it but I guess it. Next we will look at a function to solve json Chinese garbled characters.

Private function to_utf8 ($ in)
{
If (is_array ($ in )){
Foreach ($ in as $ key => $ value)
{
$ Out [$ this-> to_utf8 ($ key)] = $ this-> to_utf8 ($ value );
}
}
Elseif (is_string ($ in ))
{
If (mb_detect_encoding () ($ in )! = "UTF-8 ")
Return utf8_encode ($ in );
Else
Return $ in;
}
Else
{
Return $ in;
}
Return $ out;
}

1. Output $ usr-> username directly, and set charset = utf-8 in the header of the page. Garbled characters
2. echo json_encode ($ usr) output username = null
3. Set the page header to charset = gbk. The output is correct.-> You can confirm that the original code is gbk.
Finally, through ie, chrome, and firefox tests, we can conclude that:


1. Ensure that the page character set is consistent with the database tutorial, and the output must be normal.
2. When json_encode is executed, ensure that the data encoding is UTF-8 and json_decode is normal.
3. If you want to perform json_encode on non-UTF-8 characters, convert them to UTF-8 first.
4. When json_decode is performed on non-UTF-8 characters, do not forget to convert them to the original encoding; otherwise, garbled characters will be output !!

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.