漂亮-用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 關注
- 798 瀏覽
添加回答
舉報
0/150
提交
取消