15

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?

Ian Mackinnon
  • 12,541
  • 13
  • 50
  • 64
XMen
  • 27,697
  • 41
  • 97
  • 149

2 Answers2

40

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.

Paul Dixon
  • 287,944
  • 49
  • 307
  • 343
27

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>
Lumbendil
  • 2,896
  • 1
  • 18
  • 24