使用PHP格式化打印JSON
使用PHP格式化打印JSON
我正在构建一个PHP脚本,将JSON数据馈送到另一个脚本。我的脚本构建数据到一个大的关联数组中,然后使用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中是否有一种方法可以实现这一点,而不需要一个丑陋的hack?看起来像是 Facebook 的某个人解决了这个问题。
admin 更改状态以发布 2023年5月23日
这个函数会把JSON字符串缩进使其易于阅读。它也应该是收敛的。
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; }
PHP 5.4提供了JSON_PRETTY_PRINT
选项,可用于与json_encode()
调用一起使用。
https://php.net/manual/en/function.json-encode.php