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?
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.
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>
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