PHP output JSON and display the Chinese characters in JSON and example _php example

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 has Chinese, using the Json_encode function to be processed after the character is encoded into Unicode, How can I display Chinese in JSON? Please see below.

First, let's introduce 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 ' => ' yard farmer Hello! ');
$json = Json_encode ($arr);
echo $json;
? >

The results of the output are:

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

Here to note:

Double quotes are automatically encoded as \ In JSON, which is very well understood, in the string in JS is not allowed to come out single quotes, double quotes and back slashes.
Chinese characters are encoded as Unicode

If it is a write interface, then the direct output is enough, Chinese do not have to do processing. Wait until the client, then to the Unicode of Chinese into Chinese characters can be. But if you want to output the characters directly on the server side, we can do the following.

<?php
$arr = Array (' p1 ' => ' Nihao ', ' P2 ' =>2, ' ch ' => ' yard farmer 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 ":" Yard farmer Hello! " "}

This operation is very simple, in fact, is to match the output results, the Unicode restore to the Chinese characters.

Thank you for reading, I hope to help you, thank you for your support for this site!

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.