JSON is one of the popular data formats across all technologies. JSON handling with PHP is easier than it looks. Most of the APIs use JSON format for data interchange. For example, if you want to extract profile data from Facebook using its API, it returns it in JSON format. There is no option to ignore JSON.
Data in JSON format can be read and parsed easily compared to other data formats. There are many core functions for JSON handling with PHP.
Those built-in functions encode, write, parse, decode and convert JSON data. Those pre-defined PHP functions make our work easier.
JSON is a universal data-interchange text format that stands for JavaScript Object Notation. This is a language-independent data format.
Both human and machine readability is high for the JSON data format. The data structure can be of the two structural formats as an object or array in this format.
The above image is for easy understanding and representational purposes only. For a syntactic and formal definition, refer to the Standard ECMA-404
The JSON evolved from the JavaScript and ECMAScript programming language.
The JSON object contains an associative array of “name: value” pairs, whereas the JSON array includes a sequence of values with default numeric indexes.
In the JSON introduction, we saw that the format could be varied based on the data structure. Let us see the examples for these two JSON formats, object, and array.
JSON object format consists of a collection of key-value pairs of data. The below structure shows an example of a valid JSON object structure.
{
"FIFA_World_Cup_Winners" : {
"2018" : "France",
"2014" : "Germany",
"2010" : "Spain",
"2006" : "Italy",
"2002" : "Brazil"
}
}
The data sequence will be listed in an ordered list in a JSON array. There will be no key-value mapping. The following example shows a JSON array structure.
{
"FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}
The above example JSON lists the last five winner countries without explicit indexes. So it will be treated as an array of an ordered list of items.
JSON array will be enclosed with [ square brackets ] whereas the JSON objects are enclosed with { curly brackets }
Regarding the possible JSON structure, now we will see about JSON handling with PHP to parse data from an input file containing JSON data, as shown below.
{
"FIFA_World_Cup_finals":
[
{
"Year": "2018",
"data":
{
"Winner": "France",
"Score": "4-2",
"Runner-up": "Croatia"
}
},
{
"Year": "2014",
"data":
{
"Winner": "Germany",
"Score": "1-0",
"Runner-up": "Argentina"
}
},
{
"Year": "2010",
"data":
{
"Winner": "Spain",
"Score": "1-0",
"Runner-up": "Netherlands"
}
}
]
}
Pass this file path to the PHP file_get_contents() function and store the JSON data into a variable.
As the input JSON file contains multi-level hierarchical structural data, we have to iterate the JSON object using PHP RecursiveArrayIterator recursively.
PHP’s RecursiveArrayIterator simplifies the JSON parsing implementation with a few lines of code, as shown below. You should realize and make use of the power of PHP built-in functions.
<?php
$JSON = file_get_contents("input.json");
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($JSON, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(!is_array($val)) {
if($key == "Year") {
print "<br/>";
}
print $key." : ".$val . "<br/>";
}
}
?>
Then, this PHP JSON parsing program will return the following output to the browser.
In a previous tutorial, we have seen how to encode-decode JSON using PHP. The json_encode and json_decode PHP functions perform the encode and decode operations, respectively.
The following code block shows the syntax of the json_decode function. This function accepts JSON string input as its first parameter. Also, it takes an optional boolean value as its second parameter.
json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] ) : mixed
By sending TRUE to this optional parameter, the decoding result will be returned as an array instead of an object. The default value of this param is FALSE, as specified in the syntax.
Consider the following input JSON data. Let us see how it is decoded into an array using the json_decode() function.
<?php
$JSON = '{
"FIFA_Last_World_Cup_final":
{
"Year": "2018",
"data":
{
"Winner": "France",
"Score": "4-2",
"Runner-up": "Croatia"
}
}
}';
$outputArray = json_decode($JSON, TRUE);
print "<PRE>";
print_r($outputArray);
?>
The output array is,
The PHP json_decode function will default convert the JSON data into an object. The $assoc parameter of the json_decode function will force the output format based on the boolean value passed to it.
In the above example, we can get the decoded data as an object by removing the second parameter. The JSON to Object conversion code and the output are shown below.
<?php
$JSON = '{
"FIFA_Last_World_Cup_final":
{
"Year": "2018",
"data":
{
"Winner": "France",
"Score": "4-2",
"Runner-up": "Croatia"
}
}
}';
$outputObject = json_decode($JSON);
print "<PRE>";
print_r($outputObject);
?>
For converting a PHP array to a JSON format, the json_encode() function is used. The following code snippet specifies the PHP json_encode() function’s syntax.
json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] ) : string
This function accepts the JSON-encoded input as its first parameter. It should be specified with a JSON string while invoking json_encode to process the data conversion.
Below PHP script converts a PHP array into a JSON format. In this example, I have used an associative array which will be sent to the json_encode function.
<?php
$inputArray = array (
"FIFA_Last_World_Cup_final" => array (
"Year" => "2018",
"data" => array ( "Winner" => "France", "Score" => "4-2", "Runner-up" => "Croatia")
)
);
$encodedJSON = json_encode($inputArray, JSON_PRETTY_PRINT);
print($encodedJSON);
?>
This program will print the encoded JSON data on the browser, as shown below.
{ "FIFA_Last_World_Cup_final": { "Year": "2018", "data": { "Winner": "France", "Score": "4-2", "Runner-up": "Croatia" } } }
Note:
In this section, we will see about JSON handling with PHP and AJAX. I have used JavaScript to send the AJAX call to the PHP via an XML HTTP request.
Add the script below on the HTML page where you want to access JSON data from PHP.
The AJAX callback will get the response JSON from the PHP endpoint. In this example, the PHP endpoint is specified as the JavaScript AJAX URL by setting the action parameter in the URL query string. It calls the getJSON.php file via AJAX.
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
var JSONResponse = JSON.parse(xmlhttp.responseText);
document.write("<u>Year: "+JSONResponse.FIFA_Last_World_Cup_final.Year+"</u><br/><br/>");
document.write("Winner: "+JSONResponse.FIFA_Last_World_Cup_final.data.Winner+"<br/>");
document.write("Score: "+JSONResponse.FIFA_Last_World_Cup_final.data.Score+"<br/>");
document.write("Runner: "+JSONResponse.FIFA_Last_World_Cup_final.data.Runner+"<br/>");
}
else {
alert('Problem in parsing JSON data via AJAX');
}
}
};
xmlhttp.open("GET", "getJSON.php?action=getJSON", true);
xmlhttp.send();
</script>
The returned JSON output is received in the onreadystatechange callback. This output data is parsed with the JSON.parse method of JavaScript.
In the PHP script, the JSON data is returned to the AJAX by using the PHP print statement. Before creating the output JSON data, it checks the required action parameter sent via AJAX is not empty.
<?php
if(!empty($_POST["action"])) {
$inputArray = array (
"FIFA_Last_World_Cup_final" => array (
"Year" => "2018",
"data" => array ( "Winner" => "France", "Score" => "4-2", "Runner" => "Croatia")
)
);
$encodedJSON = json_encode($inputArray, JSON_PRETTY_PRINT);
print($encodedJSON);
exit;
}
?>
This AJAX script process the JSON response in the success callback function. In this callback, the read JSON data are used to update the UI. The output will be displayed below.
Accessing JSON feed URLs can be done in various ways. In the above example of parsing JSON file data via PHP, we have used the file_get_contents() function.
The file_get_contents() will not work on the server because of the security directives enabled with the PHP.ini configurations. So, we can also use the CURL script to extract JSON data from the remote feed URL.
The following example will show how to use PHP CURL to access the JSON feed and display data to the browser.
<?php
$JSON_feed_URL = "\path\input.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $JSON_feed_URL);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$outputArray = json_decode($response);
print "<PRE>";
print_r($outputArray);
exit;
?>
We have already seen how to convert JSON to JavaScript Objects while creating the example on JSON handling with PHP via AJAX without jQuery.
This section will see how to convert JSON data into a JavaScript Object. Also, we have to loop through the resultant Javascript Object array.
JSON to JavaScript Object conversion can be done by using various ways. As in the previous example, we can do this using JavaScript’s built-in JSON.parse() method.
Using jQuery, the $.parseJSON method will support this conversion and make it work in many obsolete web browsers. The following code uses jQuery to convert a JSON input string into a JavaScript Object.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function() {
var JSONInputData = '{ "FIFA_World_Cup_finals": [ { "Year": "2018", "data": { "Winner": "France", "Score": "4-2", "Runner-up": "Croatia" } }, { "Year": "2014", "data": { "Winner": "Germany", "Score": "1-0", "Runner-up": "Argentina" } } ] }';
var JSONObjectArray = $.parseJSON(JSONInputData);
$("#status").html("View JavaScript object structure in the browser console");
console.log(JSONObjectArray);
});
</script>
</head>
<body>
<div id="status"></div>
</body>
</html>
By running this program, we can see the JavaScript object structure in the browser’s console window, as shown below.
The following script is used to loop through the Javascript object array converted from JSON data. In this example, I have used a nested loop to parse the multi-level JSON data.
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function() {
var JSONInputData = '{ "FIFA_World_Cup_finals": [ { "Year": "2018", "data": { "Winner": "France", "Score": "4-2", "Runner-up": "Croatia" } }, { "Year": "2014", "data": { "Winner": "Germany", "Score": "1-0", "Runner-up": "Argentina" } } ] }';
var JSONObjectArray = $.parseJSON(JSONInputData);
for (var key in JSONObjectArray["FIFA_World_Cup_finals"]) {
document.write("<br/><u>" + JSONObjectArray["FIFA_World_Cup_finals"][key]["Year"]+"</u><br/>");
for (var k in JSONObjectArray["FIFA_World_Cup_finals"][key]["data"]) {
document.write(k + ": " + JSONObjectArray["FIFA_World_Cup_finals"][key]["data"][k]+"<br>");
}
}
});
</script>
This is the reverse process of the above section. JavaScript supports this conversion by using its built-in JSON.stringify method. This section lets us see an example code to learn how to use JSON.stringify with JavaScript.
<script>
var objectArray = {"FIFA_World_Cup_finals": [
{
"Year": "2018",
"data":
{
"Winner": "France",
"Score": "4-2",
"Runner-up": "Croatia"
}
},
{
"Year": "2014",
"data":
{
"Winner": "Germany",
"Score": "1-0",
"Runner-up": "Argentina"
}
}
]};
var JSONStringData = JSON.stringify(objectArray);
document.write(JSONStringData);
</script>
Besides jQuery and built-in JavaScript JSON methods, libraries can handle JSON powerfully on the client side.
For example, the JSON-js library is featured for parsing JSON with various methods. Also, it provides support to the process’s cyclical structures.
In this article, we have already seen how to access JSON data via AJAX using Javascript. In this section, we will see how to replicate the same with jQuery AJAX code for implementing this.
Add the below script on the view page where you want the JSON response from PHP via AJAX. In this script, we can see the dataType option added to initialize the jQuery AJAX default.
With the specification of this dataType:’JSON’, the AJAX callback can get and process the JSON formatted data. In this example, the AJAX URL param specifies the PHP endpoint. It calls the getJSON.php file via AJAX.
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
data: "action=getjson",
url: "getJSON.php",
dataType : "JSON",
success: function(JSONResponse){
document.write("<u>Year: "+JSONResponse.FIFA_Last_World_Cup_final.Year+"</u><br/><br/>");
document.write("Winner: "+JSONResponse.FIFA_Last_World_Cup_final.data.Winner+"<br/>");
document.write("Score: "+JSONResponse.FIFA_Last_World_Cup_final.data.Score+"<br/>");
document.write("Runner: "+JSONResponse.FIFA_Last_World_Cup_final.data.Runner+"<br/>");
}
});
});
</script>
The PHP code is identical to the previous JSON AJAX example without jQuery. Refer to the above example for the PHP script to return encoded JSON to jQuery AJAX success callback.
Fetch API is a built-in interface in JavaScript that fetches resource data from various sources. It allows remote access across the network to fetch resources.
Fetch API consists of request-response objects that send fetch params and get response body.
For fetching JSON data by using FetchAPI, the JSON resource path has to be passed to the fetch() function. The below code shows how to use JavaScript Fetch SPI to get JSON data from a file.
<script>
//Pass JSON feed URL
fetch('input.json')
.then(response => {
return response.json();
}).then(data => {
// Handle response JSON
console.log(data);
});
</script>
While processing JSON handling with PHP, there might be the possibility of error occurrences due to several reasons. For example, improper JSON syntax, exceeding depth limit, and many other.
If the error occurs, then PHP JSON functions will return NULL. In such cases, the json_last_error() function will be helpful for tracking and handling the error. This function will return a numeric value representing the JSON error code.
Some of the JSON error codes and the description are listed below.
Gone are those days of handling highly complex XML documents. Difficult schema markups and manipulating them are no longer required. Any popular API consumes and produces JSON data. It is comfortable in terms of machine processing and human understanding.
JSON has taken a higher place in the world of data interchange and will stay there for a long time as its adoption is increasing daily. I wish to highlight that PHP provides supreme support at a core level for handling JSON.
You should know those pre-defined functions and use them to make your code efficient. This article has consolidated all the primary use cases, implementations, and problem scenarios in handling JSON with PHP.
I hope you enjoyed it. Add your experience with JSON and any valuable input in the comments form below.
The best comprehensive, in-depth tutorial on JSON using PHP I have seen. In particular, the example codes are short and sweet. You are rocking.
Thank you Carell for the kind words!
Hey Vincy I learn a lot from tutorial
Thank you Pawan.
Great, I really like it! Youre awesome
Glad you like it Pablo! Thank you.
Would it be possible to add the JS solution if you include jQuery?
In this article, under the sub-heading “Read JSON via AJAX and Process”, there is a code snippet and it uses plain JavaScript solution without using jQuery. Is this what you are looking for?
This code will work irrespective of jQuery’s presence.
The transformation your blog is taking is phenomenal. I can see that things are changing exponentially. In-depth and detailed content, the narration style, everything is changing. This is how you start something, acquire knowledge, continuous improvement, take it to zenith. I must say, appreciations to you. Keep walking!
Thank you Jorge for the kind words.
It’s amazing how Vincy presents and tackles the content. I was already trying to implement JSON, but with this explanation and methods I can improve my applications.
Thank you Vincy!
Fred Zitha, from Mozambique.
Thank you Fred for the amazing words. Welcome.
This is amazing, super thanks for this Vincy.
You are most welcome, Frederick.
This is a great tutorial article on JSON. I particularly like the approach of the content presentation.
Thank you Okpara. You will see more of this kind of tutorials in the future. Keep reading.
This is great and useful article thanks for sharing your knowledge with us
Thank you Jeff.
awesome tutorial
Thank you Austin.
Everything thing you ever needed to process JSON, brilliant article!
Thank you Alan.
WOW. This is the best in-depth tutorial on JSON using PHP. Thank you
Thank you Srinivas.
Really great tutorial ! Thank you.
Welcome Marin.
Great job on the tutorial. Your site is very comprehensive and easy to follow. Excellent Job!!!
Thank you Carl.
I want to update json file on server and multiple users can read that file same time. Is it good way or not in PHP?
Hi Nitin,
To assess it, we need more information. What kind of file is it? use case etc.
I really need this, thanks for your detailed information.
Welcome Ishant.
That’s really very cool..
Thank you Michael.