I'm building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode
. Here is an example script:
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
The above code yields the following output:
{"a":"apple","b":"banana","c":"catnip"}
This is great if you have a small amount of data, but I'd prefer something along these lines:
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebook figured it out.
PHP 5.4 offers the
JSON_PRETTY_PRINT
option for use with thejson_encode()
call.http://php.net/manual/en/function.json-encode.php
This function will take JSON string and indent it very readable. It also should be convergent,
Input
Output
Code
Simple way for php>5.4: like in Facebook graph
Result in browser
If you are working with MVC
try doing this in your controller
then if you call /getLatestUsers you will get a pretty JSON output ;)
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):
Example:
This outputs:
If you are on firefox install JSONovich. Not really a PHP solution I know, but it does the trick for development purposes/debugging.