PHP JSON Data formatting method

Source: Internet
Author: User

PHP Json_encode it can be converted to an array of JSON string types. The string is not indented. China will be converted to Unicode encoding, such as \U975A\U4ED4. Read more difficulties. Today, this method Json_encode beautification treatment.

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 (' 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 such a format is very 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 ($data, $indent =null) {////Each element in an array is recursively urlencode operation, protecting Chinese characters array_walk_recurs    Ive ($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"        }    ]}

php5.4 later. 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 Json_error_utf8 (integer) exception of the UTF-8 character, perhaps due to an incorrect encoding.

This constant takes effect from PHP 5.3.1.



json_hex_tag (integer) all < and > convert to \u003c and \u003e. Effective from PHP 5.3.0. Json_hex_amp (integer) all & converted 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 "converts to \u0022.

takes effect from PHP 5.3.0. Json_force_object (integer) causes a non-associative array to output a class (OBJECT) instead of an array. The

is used especially when the array is empty and the recipient needs a Class (Object). Effective from PHP 5.3.0. The

Json_numeric_check (integer) encodes all numeric strings into numbers (numbers).

takes effect 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. The

Json_pretty_print (integer) Formats the returned data with white space characters. The

takes effect from PHP 5.4.0. Json_unescaped_slashes (integer) does the encoding/. From PHP 5.4.0 from the effective. Json_unescaped_unicode (integer) multibyte UNICODE characters encoded in literal (default encoding is \UXXXX). From PHP 5.4.0 from the effective.



PHP JSON data formatting method

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.