Pretty Print JSON In PHP

Table of Contents

Introduction

Here in this example I am going to show you how to pretty print JSON in PHP program. I will use three different kind of JSON inputs to prettify them in the output. I am going to show you how to prettify JSON string, array data, and JSON file data.

Related Post:

php pretty print json

Why do you need to prettify the JSON data?

You want to read JSON data manually when you receive this JSON data as a response of a, for example, REST service. You want to find out the issue with JSON data which might have been passed as an input to a REST service. So an ugly one liner JSON data might be very difficult to read and keep a track of a particular key/value pair with a naked eye. Sometimes you might need to share your JSON data to someone else when you are requested to do so.

Prerequisites

PHP 7.4.27

Pretty Print JSON

Let’s consider the following data in an array:

array('one' => 'AAA', 'two' => array('BBB', 'CCC'), 'three' => array('four' => 'DDD', 'five' => array('EEE', 'FFF')))

So, the one liner data is difficult to read, in fact, it’s not too difficult to read the above one liner data and you can easily figure out which key/value pairs are there. But think of a big JSON string which has many such key/value pairs and also it has deep level of nested structure or hierarchical JSON data. Certainly, it will be too difficult to read the data in a naked eye. Hence you need to prettify the JSON data which you can easily read in simple way.

To pretty print the above array data in JSON format, simple use any one of the following line of code:

echo json_encode($json, 128);

Or

echo json_encode($json, JSON_PRETTY_PRINT);

Or

echo json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Any one of the above lines will give you the following output in JSON format:

{
    "one": "AAA",
    "two": [
        "BBB",
        "CCC"
    ],
    "three": {
        "four": "DDD",
        "five": [
            "EEE",
            "FFF"
        ]
    }
}

So far so good. Now let’s say you have the data in JSON format in one line instead of in an array:

"{\"one\":\"AAA\",\"two\":[\"BBB\",\"CCC\"],\"three\":{\"four\":\"DDD\",\"five\":[\"EEE\",\"FFF\"]}}"

In this case, the json_encode() function with prettify option will not give you the pretty JSON format. Therefore, first you need to convert the JSON string into array of data and then you need to apply json_encode() function. To convert to array from JSON string, you need to use json_decode() function.

The following code will produce the expected output in pretty JSON format:

$json = json_decode("{\"one\":\"AAA\",\"two\":[\"BBB\",\"CCC\"],\"three\":{\"four\":\"DDD\",\"five\":[\"EEE\",\"FFF\"]}}");
//echo json_encode($json, 128);
//echo json_encode($json, JSON_PRETTY_PRINT);
echo json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

The above code snippets will produce the same output as before.

Finally, you may have the ugly JSON string or one liner JSON string in a file. In this case, you need to read the JSON data from the file and write pretty JSON format in the file as an output.

Let’s say the following JSON data are kept into a file called input.json in the same directory where the PHP script for pretty printing JSON is kept.

{"one":"AAA","two":["BBB","CCC"],"three":{"four":"DDD","five":["EEE","FFF"]}}

To read the input json file, I have written the following code snippets:

$filename = "input.json";
$file = fopen( $filename, "r" );
         
if( $file == false ) {
	echo ( "Error in opening file" );
	exit();
}

$filesize = filesize( $filename );
$filecontent = fread( $file, $filesize );
fclose( $file );

The $filecontent variable will hold the JSON data from the input.json file.

To prettify and write to an output json file, the following code snippet is written:

$filename = "output.json";
$file = fopen( $filename, "w" );

if( $file == false ) {
	echo ( "Error in opening new file" );	
	exit();
}
fwrite($file, json_encode(json_decode($filecontent), JSON_PRETTY_PRINT));
fclose( $file );

The fwrite() function writes the pretty JSON format using json_encode() and json_decode() functions to the output file.

The output file output.json will have the following data and the output file will be created in the same directory where PHP script is kept:

{
    "one": "AAA",
    "two": [
        "BBB",
        "CCC"
    ],
    "three": {
        "four": "DDD",
        "five": [
            "EEE",
            "FFF"
        ]
    }
}

That’s all about how to pretty print JSON content in PHP program.

Source Code

Download

Leave a Reply

Your email address will not be published.