PHP output JSON and display JSON in Chinese characters and examples

Source: Internet
Author: User
PHP output JSON and display the Chinese characters in JSON

In PHP, we often need to output the array JSON, only need to use the Json_encode function to deal with the array, but sometimes the array is in Chinese, after the use of the Json_encode function is processed after the characters are encoded into Unicode, How can I display Chinese in JSON? Please see below.

First introduce the PHP output JSON format:

One of the simplest uses is to output the array directly as JSON, as follows:

<?php$arr = Array (' p1 ' = ' ni ' hao ', ' P2 ' =>2, ' ch ' = ' = ' yards farm Hello! $json = Json_encode ($arr); Echo $json; >

The result of the output is:

{"P1": "Ni\" Hao "," P2 ": 2," ch ":" \u7801\u519c\u4f60\u597d\uff01 "}

Here to note:

Double quotes are automatically encoded as \ "in JSON, which is a good understanding that the string in JS is not allowed in single quotes, double quotes, and backslashes.
Chinese characters are encoded as Unicode

If it is a write interface, then this output is sufficient, Chinese do not need to do processing. Wait until the client, and then go to the Unicode Chinese into Chinese characters can. But if we want to output the characters directly on the server side, we can do the following.

<?php$arr = Array (' p1 ' = ' = ' Nihao ', ' P2 ' =>2, ' ch ' = ' = ' Code farm Hello! $json = Json_encode ($arr); Echo Decodeunicode ($json); function Decodeunicode ($str) {  return Preg_replace_callback ('/\\\\u ([0-9a-f]{4})/I ',    create_function (      ' $matches ',      ' Return mb_convert_encoding (Pack ("h*", $matches [1]), "UTF-8", "ucs-2be"); '    ),    $str);}? >

Output:

{"P1": "Ni\" Hao "," P2 ": 2," ch ":" Yards nong Hello! " "}

This operation is very simple, actually is to match the output results, the Unicode reverted to the Chinese characters.

Thank you for reading, hope to help everyone, thank you for the support of this site!

Related Article

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.