17

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
  • 13,381
  • 13
  • 51
  • 67
XMen
  • 29,384
  • 41
  • 99
  • 151

2 Answers2

45

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
  • 295,876
  • 54
  • 310
  • 348
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,906
  • 1
  • 19
  • 24