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
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);
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
}