Friday, November 15, 2019

Pretty-Printing JSON with PHP



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.


Answer



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




...
$json_string = json_encode($data, JSON_PRETTY_PRINT);

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...