[php] PHP "pretty print" json_encode

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?

This question is related to php json encode

The answer is


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


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


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


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to encode

Write Base64-encoded image to file Base64 Java encode and decode a string C# Base64 String to JPEG Image UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function PHP "pretty print" json_encode Convert int to ASCII and back in Python Python Unicode Encode Error How to convert a string or integer to binary in Ruby? AJAX POST and Plus Sign ( + ) -- How to Encode? How to HTML encode/escape a string? Is there a built-in?