189
down vote
accepted
PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).
This should do the job:
$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);
See
http://www.php.net/manual/en/function.json-encode.php
Note: Don't forget to echo "<pre>" before and </pre> after, if you're printing it in HTML ;)
shareimprove this answer
answered Nov 30 '12 at 4:27
petrkotek
2,55211014
10
In PHP <5.4 replace JSON_PRETTY_PRINT with 128 – Nic Cottrell Aug 19 '14 at 13:36
1
@NicCottrell doesn't work when i test it here sandbox.onlinephpfunctions.com/code/… – drzaus Aug 28 '14 at 5:15
@drzaus works for me there - I can see each key of JSON on separate line (the PHP version used on that site has even JSON_PRETTY_PRINT defined. – petrkotek Aug 28 '14 at 6:07
@beret ahh, I thought sharing it would retain the PHP setting -- change the php version to anything less than 5.4 and it should go back to "unformatted" – drzaus Aug 28 '14 at 13:29
3
Thank you for the <pre>json</pre> tip! – GisMofx Feb 18 '16 at 4:05
show 2 more comments
up vote
11
down vote
Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);
But if you really want to prettify your json... Check this out
shareimprove this answer
answered Aug 17 '11 at 18:12
sg3s
7,82022348
+1 for print_r – Michael Mior Aug 17 '11 at 19:35
@Michael Mior you should see my debugging die die(print('<pre>'.print_r($var, true).'</pre>')) it prints almost anything :p – sg3s Aug 17 '11 at 19:38
1
I usually just view the source and go with var_dump, but whatever works :) – Michael Mior Aug 17 '11 at 21:09
add a comment
up vote
4
down vote
Here's a function to pretty up your json: pretty_json