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

by Vincy. Last modified on March 20th, 2023.

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

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. The data structure can be of the two structural formats as an object or array in this format.

JSON Object Data 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.

Example of a JSON Object and Array

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.

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

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 }

JSON Handling with PHP by Parsing File Data

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.

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

JSON Handing with PHP to Decode into an Array

Decode JSON to Object

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

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

  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 encodes and decode functions will work with UTF-8 formatted strings.

Read JSON via AJAX and Process

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.

Read JSON via AJAX Output

How to Access a JSON Feed and Display Data

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

How to Convert JSON to JavaScript Object

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.

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

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

What is Fetch API?

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.

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.

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

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

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

Leave a Reply

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

↑ Back to Top

Share this page