PHP's Json_encode can convert an array into a JSON-formatted string. The string is not indented, and Chinese is converted to Unicode encoding, such as \U975A\U4ED4. It is more difficult to read by people. Now this method is json_encode on the basis of a further beautification process. Make it easy for people to read content.
1. Use Json_encode output
<?php
Header (' Content-type:application/json;charset=utf8 ');
$arr = Array (
' status ' => true,
' errmsg ' => ', ' member
' =>array (
array (
' name ' => ') Li Xiaoyao ',
' gender ' => ' man '
),
Array (
' name ' => ' Zhaoling ',
' gender ' => '
)
") );
echo Json_encode ($arr);
? >
Output:
{' Status ': true, ' errmsg ': ' ', ' member ': [{' Name ': ' \u674e\u900d\u9065 ', ' Gender ': ' \u7537 '},{' name ': ' \u8d75\u7075\ u513f "," Gender ":" \u5973 "}]}
As you can see, this format is difficult for people to read.
2. Use Jsonformat output
<?php/** JSON Data format * @param Mixed $data data * @param String $indent indent characters, default 4 spaces * @return JSON * * FU Nction Jsonformat ($data, $indent =null) {//each element of the array UrlEncode operations recursively, protect Chinese characters//View more highlights in this column: Http://www.biance
Ng.cnhttp://www.bianceng.cn/webkf/php/array_walk_recursive ($data, ' jsonformatprotect ');
JSON encode $data = Json_encode ($data);
The contents of the UrlEncode are 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; /** the array element UrlEncode * @param String $val/function 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 Array ( ' Name ' => ' Li Xiaoyao ', ' Gender ' => ' man '
), Array (' name ' => ' Zhaoling ', ' Gender ' => '));
echo Jsonformat ($arr); ?>
Output:
{
"status": True, "
errmsg": "",
"member": [
{
"name": "Li Xiaoyao",
"gender": "Male"
},
{ "
name": "Zhaoling Child",
"gender": "Female"
}
]
}