Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON indentation in PHP [duplicate]

Tags:

json

php

I want to echo JSON in with indentation in PHP, just like echo "<pre>"; indents an array.

Is there any function by which I can indent JSON like this?

like image 956
XMen Avatar asked Dec 22 '10 09:12

XMen


2 Answers

From PHP 5.4 onwards, json_encode has a JSON_PRETTY_PRINT flag

$pretty=json_encode($foo, JSON_PRETTY_PRINT);

If you're stuck with an ancient version of PHP, then the manual page for json_encode includes a user-contributed sample showing how to pretty-print JSON.

like image 84
Paul Dixon Avatar answered Oct 15 '22 20:10

Paul Dixon


In fact, json_encode has an option to do pretty-print in PHP 5.4. To use it:

<pre>
<?php echo nl2br(json_encode($yourArrayOrObject, JSON_PRETTY_PRINT)); ?>
</pre>
like image 42
Lumbendil Avatar answered Oct 15 '22 18:10

Lumbendil