How to read and print pretty JSON with PHP

29/12/2020
php
JSON is a popular data storage format to exchange data between server and browser. It is derived from JavaScript and supported by many standard programming languages. It is a human-readable file format that is easily understood by anyone if it prints with proper formatting. JSON data prints in a single line when no formatting is applied. But this type of output is not so easier to understand. So, the formatted JSON data is very important to understand the structure of the data for the reader. Pretty print is used to format the JSON data. JSON data can be represented in a more readable form for humans by using pretty printing. There are many ways to apply pretty printing in JSON data. How you can apply JSON pretty printing using PHP is shown in this tutorial by using various examples.

Example-1: Print JSON without formatting

json_encode() function of PHP is used to parse any JSON data. Create a file named exp1.php with the following code to read a simple JSON data and print the output. Here, an associative array is declared to generate JSON data. No formatting is applied for JSON data in the code. So, JSON data will be printed in a single line in JSON format.

exp1.php

<?php

//Declare the array
$courses=array("Module-1"=>"HTML","Module-2"=>"JavaScript", "Module-3"=>"CSS3",
"Module-4"=>"PHP");

//Print the array in a simple JSON format
echo json_encode($courses);
?>

Output:

The following output will appear after executing the file from the browser.

http://localhost/json/exp1.php

Example-2: Print JSON using JSON_PRETTY_PRINT option and header() function

PHP has an option named ‘JSON_PRETTY_PRINT’ which is used with json_encode() function to print JSON data with proper alignment and particular format. Create a file named exp2.php with the following code. In the code, the same array of the previous example is used to see the use JSON_PRETTY_PRINT option. header() function is used here to inform the browser about the file content. No formatting will be applied without this function.        

exp2.php

<?php
//Declare the array
$courses=array("Module-1"=>"HTML","Module-2"=>"JavaScript", "Module-3"=>"CSS3",
"Module-4"=>"PHP");

//Notify the browser about the type of the file using header function
header(‘Content-type: text/javascript’);

//Print the array in a simple JSON format
echo json_encode($courses, JSON_PRETTY_PRINT);
?>

Output:

The following output will appear after executing the file from the browser. A specific font and alignment will be applied.

http://localhost/json/exp2.php

Example-3: Print JSON using JSON_PRETTY_PRINT option and <pre> tag

The formatting that is applied in the previous example can be done by using ‘pre’ tag in place of header() function. Create a file named exp3.php with the following code. In this example, starting the ‘pre’ tag is used before generating JSON data. The output will be similar to the previous example.

 

exp3.php

<?php
$data_arr = array(‘Robin Nixon’ => ‘Learning PHP, MySQL and JavaScript ‘,
 ‘Jon Duckett’ => ‘HTML & CSS: Design and Build Web Sites’, ‘Rob Foster’ =>
 ‘CodeIgniter 2 Cookbook’);
?>
<pre>
<?php
echo json_encode($data_arr, JSON_PRETTY_PRINT);
?>
</pre>

Output:

The following output will appear after executing the file from the browser.

http://localhost/json/exp3.php

Example-4: Colorful JSON printing using the custom function

Formatted JSON data are printed by using JSON_PRETTY_PRINT option of PHP in the previous examples. But if you want to print JSON data with the custom format then it is better to use the user-defined function of PHP. How you can apply CSS in JSON data using PHP is mainly shown in this example. Create a PHP file named exp4.php with the following code. A large JSON data is used in this example that is stored in the variable, $data. A user-defined function, pretty_print() is used in the code to format the JSON data. This function has an argument that used to pass the JSON data. A for loop is used in the function to parse the JSON data and apply differently typed of formatting before printing the data.

exp4.php

<?php
//Define a large json data
$data = ‘{"quiz bank":{ "Computer": {"q1": { "question": "who is the inventor of
 computer?","options": ["Thomas Alva Edison","Charles Babbage","Blaise Pascal",
 "Philo Farnsworth"],"answer": "Charles Babbage"},{"q2": { "question":
 "which of the following is a input device?", "options": ["Printer","Scanner",
"Monitor", "Keyboard"],"answer": "Keyboard"}},"PHP": { "q1": { "question":
 "What type of language is PHP?","options": ["High Level Language","Low level
Language","Scripting Language","Assembly Language"],"answer": "Scripting Language" },
"q2": {"question": "What is the full form of PHP?","options": ["Hypertext Preprocessor",
"Personal Home Package","Hypertext Processor","Perdonal HTML Page" ],"answer":
 "Hypertext Preprocessor"} } } }’
;

//call custom function for formatting json data
echo pretty_print($data);

//Declare the custom function for formatting
function pretty_print($json_data)
{

//Initialize variable for adding space
$space = 0;
$flag = false;

//Using <pre> tag to format alignment and font
echo "<pre>";

//loop for iterating the full json data
for($counter=0; $counter<strlen($json_data); $counter++)
{

//Checking ending second and third brackets
if ( $json_data[$counter] == ‘}’ || $json_data[$counter] == ‘]’ )
{
$space–;
echo "n";
echo str_repeat(‘ ‘, ($space*2));
}
 

//Checking for double quote() and comma (,)
if ( $json_data[$counter] == ‘"’ && ($json_data[$counter1] == ‘,’ ||
 $json_data[$counter2] == ‘,’) )
{
echo "n";
echo str_repeat(‘ ‘, ($space*2));
}
if ( $json_data[$counter] == ‘"’ && !$flag )
{
if ( $json_data[$counter1] == ‘:’ || $json_data[$counter2] == ‘:’ )

//Add formatting for question and answer
echo ‘<span style="color:blue;font-weight:bold">’;
else

//Add formatting for answer options
echo ‘<span style="color:red;">’;
}
echo $json_data[$counter];
//Checking conditions for adding closing span tag
if ( $json_data[$counter] == ‘"’ && $flag )
echo ‘</span>’;
if ( $json_data[$counter] == ‘"’ )
$flag = !$flag;

//Checking starting second and third brackets
if ( $json_data[$counter] == ‘{‘ || $json_data[$counter] == ‘[‘ )
{
$space++;
echo "n";
echo str_repeat(‘ ‘, ($space*2));
}
}
echo "</pre>";
}
?>

Output:

The following output will appear after executing the file from the browser. Here, each question and answer of the JSON data will be printed with blue color and bold format and, another part will be printed with red color.

http://localhost/json/exp4.php

Conclusion

How you can print formatted JSON data by using various PHP options are tried to show in this article. Hope, the reader will be able to apply the PHP to format JSON data and generate pretty JSON output after practicing the above examples properly.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Building a Contact Form in PHP

How to create contact form using HTML, CSS and PHP A contact form is a very essential part of any website. The visitors...
28/12/2020

How to read and print pretty JSON with PHP

JSON is a popular data storage format to exchange data between server and browser. It is derived from JavaScript and supported...
29/12/2020

How to Parse JSON in PHP

The full form of JSON is JavaScript Object Notation. It is a text-based format of data like XML which is very easy to write...
28/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Tìm Hiểu Về Thuê Proxy US – Lợi Ích và Cách Sử Dụng Hiệu Quả
11/12/2024

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024

Thuê mua IPv4 giá rẻ, tốc độ nhanh, uy tín #1
28/05/2024