Php's json_encode can convert arrays into strings in json format. The string is not indented, and Chinese characters are converted to unicode encoding, for example, \ u975a \ u4ed4. Reading is difficult. Now, this method is further beautified Based on json_encode. Enables users to easily read the content.
1. Use json_encode to output
<? Phpheader ('content-type: application/json; charset = utf8'); $ arr = array ('status' => true, 'errmsg '=> '', 'member' => array ('name' => 'Li Xiaoyao ', 'gender' => 'male'), array ('name' => 'zhao lin'er ', 'Gender' => 'female '); 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. Use jsonFormat to output
<? Php/** Json data formatting * @ param Mixed $ data * @ param String $ indent character, four spaces by default * @ return JSON */function jsonFormat ($ data, $ indent = null) {// recursively perform the urlencode operation on each element in the array to protect the Chinese character array_walk_recursive ($ data, 'jsonformatprotect '); // json encode $ data = json_encode ($ data); // urldecode $ data = urldecode ($ data) The urlencode content; // 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 element * @ param String $ val */f Unction jsonFormatProtect (& $ val) {if ($ val! = True & $ val! = False & $ val! = Null) {$ val = urlencode ($ val) ;}} header ('content-type: application/json; charset = utf8 '); $ arr = array ('status' => true, 'errmsg '=> '', 'member' => array ('name' => 'Li Xiaoyao ', 'Gender' => 'male'), array ('name' => 'zhao linger ', 'gender' => 'female '))); echo jsonFormat ($ arr);?>Output:
{"Status": true, "errMsg": "", "member": [{"name": "Li Xiaoyao", "gender": "male "}, {"name": "Zhao Linger", "gender": "female"}]}