PHP Json_encode always returns the Unicode character "\u ..." Problem resolution

Source: Internet
Author: User

Recently encountered a strange thing, the first two days to write a good code, today again run is garbled. Checked, not the general meaning of garbled, but the return of Unicode encoded characters.

such as Kanji: Login failed, after Json_encode returned to:"\U767B\U5F55\U5931\U8D25"

Really angry Zajia, find a pass, found that this is a common problem, the final solution is as follows:

Normal call Json_encode ($arr), between Echo, this JSON data is handled by the following function:

public static function JSON ($STR) {
$json = Json_encode ($STR);
Return Preg_replace ("#\\\u ([0-9a-f]+) #ie", "Iconv (' UCS-2 ', ' UTF-8 ', pack (' H4 ', ' \\1 '))", $json);
}

This will no longer garbled. For a high version of PHP, you can add a parameter directly, but the lower version is not valid, so you can only do so. The complete code is as follows:

<?phpclass util{public static function JSON ($STR) {$json = Json_encode ($STR); return Preg_replace ("#\\\u ([0-9a-f]+) # ie "," iconv (' UCS-2 ', ' UTF-8 ', pack (' H4 ', ' \\1 ')) ", $json);}}? >

Invocation Example:

echo "Login Failed"; $arr = Array (); $arr [' code '] = 1; $arr [' message '] = "Login Failed"; echo $arr [' message ']; $arr [' data '] = ""; retu RN Util::json ($arr);

Reference: Http://stackoverflow.com/questions/6771938/any-way-to-return-php-json-encode-with-encode-utf-8-and-not-unicode

PHP Json_encode always returns the Unicode character "\u ..." Problem resolution

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.