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);
?>
Output:
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);
?>
Output:
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 <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 PHP file with the following script. In this example, the starting “<pre>” 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');
?>
<pre>
<?php
echo json_encode($data_arr, JSON_PRETTY_PRINT);
?>
</pre>
Output:
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 <pre> 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 = '{"quiz bank":{ "Computer": {"q1": { "question": "who is the inventor of computer?", "options": ["Thomas Alva Edison","CharlesBabbage","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","ScriptingLanguage","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
echopretty_print($data);
//Declare the custom function for formatting
functionpretty_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";
echostr_repeat(' ', ($space*2));
}
//Checking for double quote(“) and comma (,)
if( $json_data[$counter] == '"'&& ($json_data[$counter-1] == ',' || $json_data[$counter-2] == ',') )
{
echo"\n";
echostr_repeat(' ', ($space*2));
}
if( $json_data[$counter] == '"'&& !$flag )
{
if( $json_data[$counter-1] == ':' || $json_data[$counter-2] == ':' )
//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";
echostr_repeat(' ', ($space*2));
}
}
echo"</pre>";
}
?>
Output:
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
$jsondata = '{"11897":"Megha Hossain","11564":"Abir Hasan","11234":"Joya Ahmed"}';
//Encode the json value
$decoded_data = json_decode($jsondata);
header('Content-type: text/javascript');
//Print the json data after decode
echo "The output of JSON data:\n";
echo json_encode($decoded_data, JSON_PRETTY_PRINT);
?>
Output:
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
$students = file_get_contents('students.json');
//Decode the JSON data into an array
$decoded_data = json_decode($students, true);
echo "<b>ID Name Departmen Batch</b><br/>";
//Print the JSON data
foreach($decoded_data as $student) {
$ID = $student['ID'];
$name = $student['name'];
$department = $student['department'];
$batch = $student['batch'];
echo "$ID $name $department $batch<br/>";
}
?>
Output:
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<br />Brand: $brand<br />Model: $model<br />Price: $price";
}
}
//Print message if the search value not found
if($found == false)
echo"Product does not exist.";
?>
Output:
Run the previous script without any query parameter:
http://localhost/phpcode/json7.php
Run the previous script with a query parameter value that exists in the JSON file:
http://localhost/phpcode/json7.php?s=HP
Run the previous script with a query parameter value that does not exist in the JSON file:
http://localhost/phpcode/json7.php?s=Del
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.