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.
We can use the Python json module to pretty-print the JSON data. The json module is recommended to work with JSON files. We can use the dumps() method to get the pretty formatted JSON string.
JSON. stringify(obj, null, '\t'); This "pretty-prints" your JSON string, using a tab for indentation. Save this answer.
PHP has some built-in functions to handle JSON. First, we will look at the following two functions: json_encode() json_decode()
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With