漂亮-用PHP打印JSON我正在构建一个将JSON数据提供给另一个脚本的PHP脚本。我的脚本将数据构建到一个大型关联数组中,然后使用json_encode..下面是一个示例脚本:$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');header('Content-type: text/javascript');echo json_encode($data);上面的代码产生以下输出:{"a":"apple","b":"banana","c":"catnip"}如果您有少量的数据,这是很好的,但是我更喜欢这样的东西:{
"a": "apple",
"b": "banana",
"c": "catnip"}有什么方法可以在PHP中做到这一点而不受攻击呢?好像有人在脸书弄明白了。
3 回答
跃然一笑
TA贡献1826条经验 获得超6个赞
prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )
{"key1":[1,2,3],"key2":"value"}
{ "key1": [ 1, 2, 3 ], "key2": "value"}
function prettyPrint( $json ){ $result = ''; $level = 0; $in_quotes = false; $in_escape = false; $ends_line_level = NULL; $json_length = strlen( $json ); for( $i = 0; $i < $json_length; $i++ ) { $char = $json[$i]; $new_line_level = NULL; $post = ""; if( $ends_line_level !== NULL ) { $new_line_level = $ends_line_level; $ends_line_level = NULL; } if ( $in_escape ) { $in_escape = false; } else if( $char === '"' ) { $in_quotes = !$in_quotes; } else if( ! $in_quotes ) { switch( $char ) { case '}': case ']': $level--; $ends_line_level = NULL; $new_line_level = $level; break; case '{': case '[': $level++; case ',': $ends_line_level = $level; break; case ':': $post = " "; break; case " ": case "\t": case "\n": case "\r": $char = ""; $ends_line_level = $new_line_level; $new_line_level = NULL; break; } } else if ( $char === '\\' ) { $in_escape = true; } if( $new_line_level !== NULL ) { $result .= "\n".str_repeat( "\t", $new_line_level ); } $result .= $char.$post; } return $result;}
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
echo json_encode($results, JSON_PRETTY_PRINT);
header('Content-Type: application/json');
- 3 回答
- 0 关注
- 766 浏览
添加回答
举报
0/150
提交
取消