PHP "pretty print" json_encode

PhpJsonEncode

Php Problem Overview


> Possible Duplicate:
> Pretty-Printing JSON with PHP

I'm working on a script that creates a JSON file. Right now I'm just using json_encode (PHP 5.2.x) to encode an array into JSON output. Then I print the returned value to a file and save it. Problem is that the client wants to be able to open these JSON files for readability, so I'd like to add line breaks in and "pretty print" the JSON output. Any ideas on how to do this? My only other alternative that I can see is to not use json_encode at all and just write the file contents manually and add in my own line breaks for each line.

Here's what I get:

{"product_name":"prod1","val1":1,"val2":8}

Here's what I want:

{
  "product_name":"prod1",
  "val1":1,
  "val2":8
}

I suppose I could also just replace every comma with a command followed by a \n, and same for the brackets... Thoughts?

Php Solutions


Solution 1 - Php

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 to preserve formatting ;)

Solution 2 - Php

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

Solution 3 - Php

Here's a function to pretty up your json: pretty_json

Solution 4 - Php

And for PHP 5.3, you can use this function, which can be embedded in a class or used in procedural style:

http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrianView Question on Stackoverflow
Solution 1 - PhppetrkotekView Answer on Stackoverflow
Solution 2 - Phpsg3sView Answer on Stackoverflow
Solution 3 - PhpCam TullosView Answer on Stackoverflow
Solution 4 - PhpbohwazView Answer on Stackoverflow