- Pretty Print the JSON in PHP
- Use the HTML Tag and the JSON_PRETTY_PRINT Option to Prettify the JSON String in PHP
- Use the application/json and JSON_PRETTY_PRINT Options to Prettify the JSON String in PHP
- Use the json_encode() and json_decode() Functions to Prettify the JSON String in PHP
- Related Article - PHP JSON
- How to Read and Print Pretty JSON With PHP
- Prerequisites:
- Example 1: Print JSON Without Formatting
- Example 2: Print JSON Using JSON_PRETTY_PRINT and header()
- Example 3: Print JSON Using JSON_PRETTY_PRINT and tag
- Example 4: Print JSON Using JSON_PRETTY_PRINT and Custom Function
- Example 5: Print JSON Using json_encode() and json_decode()
- Example 6: Print the Content of a JSON File Using json_decode()
- Example 7: Reading JSON File of Random Key Values
- Conclusion
- About the author
- Fahmida Yesmin
Pretty Print the JSON in PHP
This article will introduce different methods to prettify the raw JSON string in PHP.
Use the HTML Tag and the JSON_PRETTY_PRINT Option to Prettify the JSON String in PHP
We can use the json_encode() function to convert a value to a JSON format. We can encode indexed array, associative array, and objects to the JSON format. The json_encode() function has a option JSON_PRETTY_PRINT which prettifies the JSON string. We can specify the string to be prettified and then the option in the json_encode() function. It will add some spaces between the characters and makes the string looks better. However, we can use the HTML tags to indent the strings to the new line. We will prettify an associative array in the example below. The tag preserves the line break after each key-value pair in the string.
For example, create an associative array in the variable $age . Write the keys Marcus , Mason , and Jadon and the values 23 , 19 , and 20 . Next, use the json_encode() function on the $age variable and write the option JSON_PRETTY_PRINT as the second parameter and store the expression in $json_pretty variable. Then, echo the variable enclosing it with the HTML tag.
$age = array("Marcus"=>23, "Mason"=>19, "Jadon"=>20) $json_pretty = json_encode($age, JSON_PRETTY_PRINT); echo ""
.$json_pretty."";
"Marcus": 23, "Mason": 19, "Jadon": 20 >
Use the application/json and JSON_PRETTY_PRINT Options to Prettify the JSON String in PHP
We can use the header() function to set the Content-Type to application/json to notify the browser type. It will display the data in JSON format. We can use the JSON_PRETTY_PRINT option as in the first method to prettify the string. We will use the same associative array for the demonstration. We can use the json_encode() function as in the first method.
For example, write the header() function and set the Content-Type to application/json . In the next line, use the json_encode() function with the JSON_PRETTY_PRINT option on the array as we did in the first method. As a result, we will get a prettified version of JSON data in each new line.
$age = array("Marcus"=>23, "Mason"=>19, "Jadon"=>20); header('Content-Type: application/json'); echo json_encode($age, JSON_PRETTY_PRINT); ?>
"Marcus": 23, "Mason": 19, "Jadon": 20 >
Use the json_encode() and json_decode() Functions to Prettify the JSON String in PHP
We can use the json_encode() function with the json_decode() function and the JSON_PRETTY_PRINT as the parameters to prettify the JSON string in PHP. We also use the header() function like in the second method to notify the browser about the JSON format. We will prettify a JSON object in the following example. We will take the JSON object and decode it using the json_decode() function and then will encode it with the json_encode() function along with the JSON_PRETTY_PRINT option.
For example, set the Content-Type to application/json as we did in the method above. Create a variable $json1 and store a raw JSON object in it. Then, use the json_decode() function on the variable $json1 . Use the decoded JSON object as the first parameter to the json_encode() function and the JSON_PRETTY_PRINT option as the second parameter. Store the expression in a $json2 variable and echo it.
header('Content-Type: application/json'); $json1 = ''; $json2 = json_encode(json_decode($json1), JSON_PRETTY_PRINT); echo $json2;
"a": 10, "b": 20, "c": 30, "d": 40, "e": 50 >
Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.
Related Article - PHP JSON
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 by many standard programming languages. It is a human-readable file format that anyone quickly understands 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 easier to understand. So, the formatted JSON data is very important in order for the reader to understand the structure of the data. 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. The ways to apply JSON pretty-printing using PHP are shown in this tutorial through various examples.
Prerequisites:
The examples of this tutorial have been checked for PHP version 8+. So, you have to install PHP 8.0 and an Apache server before practicing the examples of this tutorial.
Example 1: Print JSON Without Formatting
The json_encode() function of PHP is used to parse any JSON data. Create a PHP file with the following script to read a simple JSON data and print the output. Here, an associative array has been declared to generate the JSON data. No formatting is applied for JSON data in the script.Thus, JSON data will be printed in a single line.
//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
echojson_encode ( $courses ) ;
?php>
The following output will appear after executing the previous script from the browser:
Example 2: Print JSON Using JSON_PRETTY_PRINT and header()
PHP has an option named “JSON_PRETTY_PRINT” used with json_encode() function to print JSON data with proper alignment and particular format. Create a PHP file with the following script. Here, the JSON_PRETTY_PRINT option has been used to print the JSON data. The header() function is used here to inform the browser about the file content. No formatting will be applied without this function.
//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
echojson_encode ( $courses , JSON_PRETTY_PRINT ) ;
?>?php>
The following output will appear after executing the previous script from the browser. A specific font and alignment have been applied here:
Example 3: Print JSON Using JSON_PRETTY_PRINT and tag
The formatting that is applied in the previous example can be done by using “pre>” tag in place of header() function. Create a PHP file with the following script. In this example, the starting “” tag is used before generating JSON data.
$data_arr = array ( 'Robin Nixon' => 'Learning PHP, MySQL and JavaScript ' , 'Jon Duckett' => 'HTML & CSS: Design and Build Web Sites' , 'Rob Foster' => 'CodeIgniter 2 Cookbook' ) ;
echo json_encode ( $data_arr , JSON_PRETTY_PRINT ) ;
The following output will appear after executing the previous script from the browser. The output looks similar to the previous example, as shown below.
Example 4: Print JSON Using JSON_PRETTY_PRINT and Custom Function
Formatted JSON data are printed using the JSON_PRETTY_PRINT option and the tag in the previous examples. But if you want to print JSON data with the custom format, it is better to use the user-defined function of PHP. This example shows how you can apply CSS in JSON data using PHP. Create a PHP file with the following script. An extensive JSON data has been used in this example that is stored in the variable, $data. A user-defined function, pretty_print() has been used in the code to format the JSON data. This function has an argument that has been used to pass the JSON data. A for loop has been used to parse the JSON data and apply formatting before printing the data.
//Define a large json data
$data = ',>,"PHP": < "q1": < "question": "What type of language is PHP?","options": ["High Level Language","Low level Language","ScriptingLanguage","Assembly Language"],"answer": "Scripting Language" >,"q2": > > >' ;
//call custom function for formatting json data
echopretty_print ( $data ) ;
//Declare the custom function for formatting
functionpretty_print ( $json_data )
The following output will appear after executing the previous script from the browser. Here, each question and answer of the JSON data has been printed with blue color and bold format, and another part has been printed with red color:
Example 5: Print JSON Using json_encode() and json_decode()
Create a PHP file with the following script to know the way of printing the JSON data by using the json_encode() and json_decode() functions.
//Define json data into a variable
//Print the json data after decode
echo "The output of JSON data: \n " ;
echo json_encode ( $decoded_data , JSON_PRETTY_PRINT ) ;
The following output will appear after executing the previous script from the browser:
Example 6: Print the Content of a JSON File Using json_decode()
In the previous examples, JSON data have been declared inside the PHP script. But the content of a JSON file can be parsed by using PHP script. Create a JSON file named students.json with the following content:
[{
"ID" : "0111897" ,
"name" : "Walliur Rahman" ,
"department" : "CSE" ,
"batch" : "30th"
} ,
{
"ID" : "0111456" ,
"name" : "MinhazKazi" ,
"department" : "CSE" ,
"batch" : "30th"
} ,
{
"ID" : "0111897" ,
"name" : "Akramasouchi" ,
"department" : "CSE" ,
"batch" : "30th"
}
]
Create a PHP file with the following script to read the students.json file by using the file_get_contents() and json_decode() functions. Next, the foreach loop has been used to print the JSON data in a formatted way.
//Read the content of a JSON file
//Decode the JSON data into an array
$decoded_data = json_decode ( $students , true ) ;
echo "ID Name Departmen Batch
" ;
foreach ( $decoded_data as $student ) {
$department = $student [ 'department' ] ;
echo " $ID $name $department $batch
" ;
The following output will appear after executing the previous script from the browser:
Example 7: Reading JSON File of Random Key Values
The content of the JSON file can be accessed based on key-value and is required when the JSON file contains random keys. Create a JSON file named randomKey.json with the following content:
{
"7856" : {
"name" : "Mobile" ,
"brand" : "Samaung" ,
"model" : "J4" ,
"price" : 500
} ,
"4320" : {
"name" : "Laptop" ,
"brand" : "HP" ,
"model" : "Pavilion 15" ,
"price" : 1000
} ,
"9067" : {
"name" : "Tablet" ,
"brand" : "Asus" ,
"model" : "CT100PA" ,
"price" : 200
} ,
"1675" : {
"name" : "Desktop" ,
"brand" : "Dell" ,
"model" : "None" ,
"price" : 700
}
}
Create a PHP file with the following script to read the randomKey.json file by using the file_get_contents() and json_decode() functions. Next, the foreach loop has been used to search particular product information based on the search value given in the query parameter.
//Read the JSON file
$randomKey = file_get_contents ( 'randomKey.json' ) ;
//Initialize the variable
$found = false ;
//Convert JSON string into the array
$decoded_json = json_decode ( $randomKey , true ) ;
//Read the search value from the URL
if ( isset ( $_GET [ 's' ] ) )
$search_product = $_GET [ 's' ] ;
else
{
echo "Nothing to search" ;
exit ;
}
//Iterate the JSON value and search the brand
foreach ( $decoded_jsonas $k => $v ) {
$brand = $decoded_json [ $k ] [ "brand" ] ;
if ( $brand == $search_product )
{
$name = $decoded_json [ $k ] [ "name" ] ;
$model = $decoded_json [ $k ] [ "model" ] ;
$price = $decoded_json [ $k ] [ "price" ] ;
$found = true ;
echo "Product Name: $name
Brand: $brand
Model: $model
Price: $price " ;
}
}
//Print message if the search value not found
if ( $found == false )
echo "Product does not exist." ;
Run the previous script without any query parameter:
Run the previous script with a query parameter value that exists in the JSON file:
Run the previous script with a query parameter value that does not exist in the JSON file:
Conclusion
The different ways to print formatted JSON data by using various PHP scripts have been discussed in this tutorial. Hopefully, the PHP users will be able to format JSON data and generate pretty JSON output using PHP script after practicing the examples provided correctly. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.