Pretty-Printing JSON with PHP
I realize this question is asking about how to encode an associative array to a pretty-formatted JSON string, so this doesn't directly answer the question, but if you have a string that is already in JSON format, you can make it pretty simply by decoding and re-encoding it (requires PHP >= 5.4):
$json = json_encode(json_decode($json), JSON_PRETTY_PRINT);
Example:
header('Content-Type: application/json');
$json_ugly = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$json_pretty = json_encode(json_decode($json_ugly), JSON_PRETTY_PRINT);
echo $json_pretty;
This outputs:
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
PHP 5.4 offers the JSON_PRETTY_PRINT
option for use with the json_encode()
call.
http://php.net/manual/en/function.json-encode.php
<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);
Many users suggested that you use
echo json_encode($results, JSON_PRETTY_PRINT);
Which is absolutely right. But it's not enough, the browser needs to understand the type of data, you can specify the header just before echo-ing the data back to the user.
header('Content-Type: application/json');
This will result in a well formatted output.
Or, if you like extensions you can use JSONView for Chrome.
This function will take JSON string and indent it very readable. It also should be convergent,
prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )
Input
{"key1":[1,2,3],"key2":"value"}
Output
{
"key1": [
1,
2,
3
],
"key2": "value"
}
Code
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;
}