<?php
/** Json数据格式化
* @param Mixed $data 数据
* @param String $indent 缩进字符,默认4个空格
* @return JSON
*/
function jsonFormat($data, $indent=null){
// 缩进处理
$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;
}
header(‘content-type:application/json;charset=utf8‘);
$json_string = file_get_contents(‘json_string.txt‘);
echo jsonFormat($json_string);
?>
json string : { "people": [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }]}