A method for formatting PHP JSON data

Source: Internet
Author: User
Tags php session php json urlencode
PHP's Json_encode can convert an array to a JSON-formatted string. The string is not indented, and Chinese is converted to Unicode encoding, such as \U975A\U4ED4. It is difficult for people to read. Now this method is json_encode on the basis of a beautification process. Make it easy for people to read content.

1. Using the Json_encode output

<?phpheader (' Content-type:application/json;charset=utf8 '); $arr = Array (    ' status ' = = True,    ' errmsg ' = > ',    ' member ' =>array (        array (            ' name ' = ' Lee Xiaoyao ',            ' gender ' = ' man '        ),        Array (            ' name ' = ' Zhaoling ',            ' gender ' = ' women ')        )    ; Echo Json_encode ($arr);? >

Output:

{"Status": True, "errmsg": "", "Member": [{"Name": "\u674e\u900d\u9065", "Gender": "\u7537"},{"name": "\u8d75\u7075\ u513f "," Gender ":" \u5973 "}]}

It can be seen that this format is difficult for people to read.

2. Using the Jsonformat output

<?php/** JSON Data format * @param Mixed $data data * @param String $indent indent characters, default 4 spaces * @return Json*/function Jsonformat ($d    ATA, $indent =null) {//each element in the array is recursively urlencode, protecting Chinese characters array_walk_recursive ($data, ' jsonformatprotect ');    JSON encode $data = Json_encode ($data);    The content of the UrlEncode is UrlDecode $data = UrlDecode ($data);    Indent processing $ret = ';    $pos = 0;    $length = strlen ($data); $indent = Isset ($indent)?    $indent: ";    $newline = "\ n";    $prevchar = ";    $outofquotes = true;        for ($i =0; $i <= $length; $i + +) {$char = substr ($data, $i, 1);        if ($char = = ' "' && $prevchar! = ' \ \ ') {$outofquotes =! $outofquotes;            }elseif (($char = = '} ' | | $char = = '] ') && $outofquotes) {$ret. = $newline;            $pos--;            for ($j =0; $j < $pos; $j + +) {$ret. = $indent;                }} $ret. = $char;  if ($char = = ', ' | | $char = = ' {' | | $char = = ' [') && $outofquotes) {          $ret. = $newline;            if ($char = = ' {' | | $char = = ' [') {$pos + +;            } for ($j =0; $j < $pos; $j + +) {$ret. = $indent;    }} $prevchar = $char; } return $ret;} /** urlencode* The array elements @param String $val */function jsonformatprotect (& $val) {if ($val!==true && $val!==fals    E && $val!==null) {$val = UrlEncode ($val); }}header (' Content-type:application/json;charset=utf8 '); $arr = Array (' status ' = = True, ' errmsg ' = = ', ' mem            ber ' =>array (Array (' name ' = ' Lee Xiaoyao ', ' gender ' = ' m '), Array ( ' Name ' = ' Zhaoling ', ' gender ' = ' women ')); Echo Jsonformat ($arr);? >

Output:

{    "status": True,    "errmsg": "",    "member": [        {            "name": "Li Xiao",            "gender": "Male"        },        {            "name": "Zhaoling",            "gender": "Female"        }    ]}

After php5.4 , Json_encode added several constant parameters such as json_unescaped_unicode ,json_pretty_print and so on. Make it easier to display Chinese and formatting.

Header (' Content-type:application/json;charset=utf8 ');    $arr = Array (      ' status ' = ' = ', '      errmsg ' = ', '      member ' =>array ('              name ' = ') ' Li Carefree ',              ' gender ' = ' man '          ),          Array (              ' name ' = ' Zhaoling ',              ' gender ' = ' "female '  ));    Echo Json_encode ($arr, json_unescaped_unicode| Json_pretty_print);


Output:

{    "status": True,    "errmsg": "",    "member": [        {            "name": "Li Xiao",            "gender": "Male"        },        {            "name": "Zhaoling",            "gender": "Female"        }    ]}


JSON constant Parameter Description:

The following constants represent the type of error returned by Json_last_error ().

Json_error_none (integer) No error occurred. Effective from PHP 5.3.0. Json_error_depth (integer) reached the maximum stack depth. Effective from PHP 5.3.0. Json_error_state_mismatch (integer) appears underflow (underflow) or pattern mismatch. Effective from PHP 5.3.0. Json_error_ctrl_char (integer) controls the character error, possibly the wrong encoding. Effective from PHP 5.3.0. Json_error_syntax (integer) syntax error. Effective from PHP 5.3.0. The UTF-8 character of the Json_error_utf8 (integer) exception, perhaps because of an incorrect encoding. This constant takes effect from PHP 5.3.1.


The following constants can be used in conjunction with the form option of Json_encode ().

Json_hex_tag (integer) all < and > convert to \u003c and \u003e. Effective from PHP 5.3.0. Json_hex_amp (integer) All & Convert to \u0026. Effective from PHP 5.3.0. Json_hex_apos (integer) All ' converted to \u0027. Effective from PHP 5.3.0. Json_hex_quot (integer) All "Convert to \u0022. Effective from PHP 5.3.0. Json_force_object (integer) causes a non-associative array to output a class (OBJECT) instead of an array. This is especially useful when the array is empty and the recipient needs a Class (Object). Effective from PHP 5.3.0. Json_numeric_check (integer) encodes all numeric strings into numbers (numbers). Effective from PHP 5.3.3. Json_bigint_as_string (integer) encodes a large number as the original character value. Effective from PHP 5.4.0. Json_pretty_print (integer) Formats the returned data with whitespace characters. Effective from PHP 5.4.0. Json_unescaped_slashes (integer) do not encode/. Effective from PHP 5.4.0. Json_unescaped_unicode (integer) literally encodes multibyte UNICODE characters (encoded as \uxxxx by default). Effective from PHP 5.4.0.

This article explains the PHP JSON data format method, more relevant content please pay attention to the PHP Chinese web.

Related recommendations:

About PHP Session read-write lock related content

Using PHP to optimize the number of daffodils

How to verify your ID number with PHP


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.