JSON Handling with PHP: How to Encode, Write, Parse, Decode and Convert

Last modified on January 31st, 2019 by Vincy.

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. 

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.

What is JSON?

JSON is a universal data-interchange text format which 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 format that is in the form of an object or array.

JSON Object Data Format

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. Below structure shows the 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 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 about 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 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.

Parsing JSON File with PHP Output

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.

<?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,

JSON Handing with PHP to Decode into an Array

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 is 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);
?>

JSON to Object Conversion Output

JSON to Object Conversion using 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. 

<?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);
?>

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 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.

<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 the JavaScript.

In the PHP script, the JSON data is returned to the AJAX by using 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 as below.

Read JSON via AJAX Output

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 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.

<?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;
?>

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 as 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 working 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.

JSON to JavaScript Object Conversion

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.

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

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.

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

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

For example, the JSON-js library is a featured one for parsing JSON with various methods. Also, it provides support to process with 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.

<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 same as we have used in the previous JSON AJAX example without jQuery. Refer 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 the various source. 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. 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>

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, exceed 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 tracing and handling the error. This function will return a numeric value representing the JSON error code. 

Some of the JSON error code 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 the PHP provides supreme support at 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.

Comments to “JSON Handling with PHP: How to Encode, Write, Parse, Decode and Convert”

Leave a Reply to Fred Zitha Cancel reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this Article