[ Solved – 7 Answers ] PHP – Pretty-Printing JSON with PHP
Table Of Content
We build a PHP script that feeds JSON data to another script. ur script builds data into a large associative array, and then outputs the data using json_encode.
Here is an example script:
- The above code yields the following output:
- This is great if you have a small amount of data, but I’d prefer something along these lines:
- Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebook figured it out.
- php json pretty-print
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
This function will take JSON string and indent it very readable. It also should be convergent,
Input
Output
Code:
[ad type=”banner”]We just used the json formatting code here:
http://recursive-design.com/blog/2008/03/11/format-json-with-php/
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.
- This will result in a well formatted output.
- Or, if you like extensions you can use JSONView for Chrome.
Simple way for php>5.4:
Result in browser
[ad type=”banner”]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):
easy explanation
easy to understand