How to handle JSON response in PHP?

// Encode some data with a maximum depth of 4 (array -> array -> array -> string)
$json = json_encode(
array(
1 => array(
'English' => array(
'One',
'January'
),
'French' => array(
'Une',
'Janvier'
)
)
)
);

// Show the errors for different depths.
var_dump(json_decode($json, true, 4));
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;

var_dump(json_decode($json, true, 3));
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;
?>

JSON is one of the popular data formats across all technologies. JSON handling with PHP is easier than it looks. Most of the APIs uses JSON format for data interchange. For example, if you want to extract profile data from Facebook using its API,  it returns the data 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 are used to encode, write, parse, decode and convert JSON data. Those pre-defined PHP functions make our work easier.

How to handle JSON response in PHP?

What is JSON?

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. In this format, the data structure can be of the two structural formats that is in the form of an object or array.

How to handle JSON response in PHP?

The JSON object contains an associative array of “name: value” pairs whereas the JSON array contains a sequence of values with default numeric indexes.

The JSON is evolved from the JavaScript and ECMAScript programming language. Standard ECMA-404 contains the specification for a valid JSON syntax.

Example of a JSON Object and Array

In the JSON introduction, we saw that the format can be varied based on the data structure. Let us see the examples for these two JSON formats object and array.

Example of a valid JSON Object

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"
     }
}

Example of a JSON Array

In a JSON array, the sequence of data will be listed in an ordered list. There will be no key-value mapping.  The following example shows a JSON array structure.

{
    "FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}

In the above example JSON, the last five winner countries are listed 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 }

JSON Handling with PHP by Parsing File Data

With the reference to the possible JSON structure, now we are going to 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 recursively iterate the JSON object using PHP RecursiveArrayIterator.

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.

 $val) {
    if(!is_array($val)) {
        if($key == "Year") {
            print "
"; } print $key." : ".$val . "
"; } } ?>

Then, this PHP JSON parsing program will return the following output to the browser.

How to handle JSON response in PHP?

How to Decode JSON to Array

In a previous tutorial, we have seen how to encode-decode JSON using PHP. The json_encode and json_decode PHP functions are used to 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 accepts 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 in a form of 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 json_decode() function.

";
print_r($outputArray);
?>

The output array is,

How to handle JSON response in PHP?

Decode JSON to Object

By default, the PHP json_decode function will 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, by removing the second parameter we can get the decoded data in the form of an object. The JSON to Object conversion code and the output are shown below.

";
print_r($outputObject);
?>

JSON to Object Conversion Output

How to handle JSON response in PHP?

Convert PHP Array to JSON

For converting a PHP array to a JSON format, json_encode() function is used. 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 mandatorily be specified with a JSON string while invoking json_encode to process the data conversion.

Below PHP script is used to convert 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.

 array (
                    "Year" => "2018",
                    "data" => array ( "Winner" => "France", "Score" => "4-2", "Runner-up" => "Croatia")
                )
            );

$encodedJSON = json_encode($inputArray, JSON_PRETTY_PRINT);

print($encodedJSON);
?>

By running this program, the encoded JSON data will be printed on the browser as shown below.

{ "FIFA_Last_World_Cup_final": { "Year": "2018", "data": { "Winner": "France", "Score": "4-2", "Runner-up": "Croatia" } } }

Note:

  1. The options parameter of the PHP JSON encode/decode functions will accept the JSON constants. The behavior of the JSON constants is described on the linked external page.
  2. PHP JSON encode and decode functions will work with UTF-8 formatted strings.

Read JSON via AJAX and Process

In this section, we are going to 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 below script on the HTML page from where you want to access JSON data returned by 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.

{
    "FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}
0

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.

{
    "FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}
1

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.

How to handle JSON response in PHP?

How to Access a JSON Feed and Display Data

Accessing JSON feed URL can be done in various ways. In the above example on parsing JSON file data via PHP, we have used file_get_contents() function.

The file_get_contents() will not work on the server because of the security directives enable 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 JSON feed and display data to the browser.

{
    "FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}
2

How to Convert JSON to JavaScript Object

We have already seen how to convert JSON to JavaScript Object while creating the example on JSON handling with PHP via AJAX without jQuery.

In this section, we are going to 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 like in the previous example, we can do this by 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.

{
    "FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}
3

By running this program, we can see the JavaScript object structure in the browser’s console window as shown below.

How to handle JSON response in PHP?

Loop through the JSON object using Javascript

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.

{
    "FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}
4

Convert JavaScript Object to JSON

This is the reverse process of the above section. JavaScript supports this conversion by using its built-in JSON.stringify method. In this section let us see an example code to learn how to use JSON.stringify with JavaScript.

{
    "FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}
0

Apart from the jQuery and built-in JavaScript JSON methods, there are libraries available to powerfully handle JSON on the client-side.

For example, the JSON-js library is a featured one for parsing JSON with various methods. Also, it provides support to processes cyclical structures.

How to Read JSON using jQuery?

In this article, we have already seen how to access JSON data via AJAX using Javascript. In this section, we are going to 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 the JSON formatted data and process it. In this example, the PHP endpoint is specified in the AJAX URL param. It calls the getJSON.php file via AJAX.

{
    "FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}
4

The PHP code is the same as we have used in the previous JSON AJAX example without jQuery. Refer to the above example to see the PHP script to return encoded JSON to jQuery AJAX success callback.

What is Fetch API?

Fetch API is a built-in interface in JavaScript used to fetch resource data from various sources. It allows remote access across the network to fetch resources.

Fetch API consists of request-response objects that are used to send fetch params and get response body respectively.

How to Use JavaScript Fetch API to Get JSON

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.

{
    "FIFA_Last_Five_Winners" : ["France","Germany","Spain","Italy","Brazil"]
}
0

JSON Error Handling and Testing

While processing JSON handling with PHP, there might be the possibility of error occurrences due to several reasons. For example, improper JSON syntax, exceeding of depth limit and many other.

If the error occurred, 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.

  • JSON_ERROR_NONE – No error has occurred.
  • JSON_ERROR_DEPTH – The maximum stack depth has been exceeded.
  • JSON_ERROR_STATE_MISMATCH – Occurs with underflow or with the modes mismatch.
  • JSON_ERROR_CTRL_CHAR – Control character error, possibly incorrectly encoded.
  • JSON_ERROR_SYNTAX – Syntax error.
  • JSON_ERROR_UTF8 – Malformed UTF-8 characters, possibly incorrectly encoded.
  • JSON_ERROR_UTF8 – Malformed UTF-8 characters, possibly incorrectly encoded.

Conclusion

Gone are those days of handling high complex XML documents. Difficult schema markups and manipulating them are no longer required. Any popular API consumes and produces JSON data. It is both comfortable in terms of machine processing and human understanding.

JSON has taken a higher place in the world of data interchange and it is going to stay there for long as the adoption is increasing day by day. The important point I wish to highlight is that PHP provides supreme support at a core level for handling JSON.

You should be aware of those pre-defined functions and make use of it so that your code will be efficient. This article has consolidated all the major use cases, implementations and problem scenarios in handling JSON with PHP.

Hope you enjoyed it. Add your experience with JSON and any valuable input in the comments form below.

How to work with JSON response in PHP?

Example explained:.
Define an object containing a "limit" property and value..
Convert the object into a JSON string..
Send a request to the PHP file, with the JSON string as a parameter..
Wait until the request returns with the result (as JSON).
Display the result received from the PHP file..

How to decode JSON response in PHP?

PHP and JSON.
The json_encode() function is used to encode a value to JSON format..
The json_decode() function is used to decode a JSON object into a PHP object or an associative array..
The json_decode() function returns an object by default. ... .
You can also loop through the values with a foreach() loop:.

How do I process a JSON response?

To parse a JSON response, we have to first convert the response into a string. To obtain the response we need to use the methods - Response. body or Response. getBody.

How to read a JSON file in PHP?

Read a JSON File in PHP​ We parse the JSON file using native PHP functions: Open and read the file's content with file_get_contents($path) Convert the JSON string to an associative array with json_decode($jsonString, true) Print the associative array with var_dump($jsonData)