English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to encode and decode JSON data in PHP.
JSON represents JavaScript Object Notation. JSON is a standard lightweight data exchange format that can be parsed and generated quickly and easily.
Like JSON and XML, it is a text-based format that is easy to write and understand for both humans and computers, but unlike XML, the bandwidth occupied by the JSON data structure is less than that of the XML version. JSON is based on two basic structures:
Object:This is defined as/A collection of value pairs (i.e., key:value). Each object starts with a left curly brace { and ends with a right curly brace }./Value pairs are separated by commas, .
Array:defined as an ordered list of values. Arrays start with a left parenthesis and end with a right parenthesis [ ]. Values are separated by commas, .
In JSON, keys are always strings, and values can bestring,number,trueorfalse,nullevenobjectorarray. Strings must be enclosed in double quotes (" ") and can contain escape characters such as \n, \t, and \. A JSON object may look like this:
{ "book": { "name": "Harry Potter and the Goblet of Fire", "author": "J. K. Rowling", "year": 2000, "genre": "Fantasy Fiction", "bestseller": true } }
The following is an example of a JSON array:
{ "fruits": [ "Apple", "Banana", "Strawberry", "Mango" ] }
Hint:Data exchange format is a text format used for exchanging or exchanging data between different platforms and operating systems. JSON is the most popular and lightweight data exchange format in web applications.
The JSON data structure is very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode(). These two functions are only applicable to UTF-8Encoded string data.
In PHP, the json_encode() function is used to encode values into JSON format. The encoded value can be any value except resources.PHP data types, such as database or file handles. The following example demonstrates how toPHP associative arrayEncoded as JSON object:
<?php //Associative array $marks = array("Peter":65, "Harry":80, "John":78, "Clark":90); echo json_encode($marks); ?>Test and see‹/›
The output of the above example will be as follows:
{"Peter":65,"Harry":80,"John":78"Clark":90}
Similarly, you can alsoPHP indexed arrayEncoded as JSON array, as follows:
<?php //Indexed array $colors = array("Red", "Green", "Blue", "Orange", "Yellow"); echo json_encode($colors); ?>Test and see‹/›
The output of the above example will be as follows:
["Red","Green","Blue","Orange","Yellow"]
You can also force the json_encode() function to return PHP indexed arrays as JSON objects by using the JSON_FORCE_OBJECT option, as shown in the following example:
<?php //Indexed array $colors = array("Red", "Green", "Blue", "Orange"); echo json_encode($colors, JSON_FORCE_OBJECT); ?>Test and see‹/›
The output of the above example will be as follows:
{"0":"Red","1:"Green",2:"Blue",3:"Orange"
As you can see in the above example, non-associative arrays can be encoded as arrays or objects. However, associative arrays are always encoded as objects.
Decoding JSON data is as simple as encoding it. You can use the PHP json_decode() function to convert a JSON-encoded string to an appropriate PHP data type. The following example demonstrates how to decode or convert a JSON object orPHP object.
<?php //Store JSON data in a PHP variable $json = '{"Peter":65,"Harry":80,"John":78"Clark":90}'; var_dump(json_decode($json)); ?>Test and see‹/›
The output of the above example is as follows:
object(stdClass)#1 (4) { ["Peter"]=> int(65) ["Harry"]=> int(8) ["John"]=> int(78) ["Clark"]=> int(90)}
By default, the json_decode() function returns an object. However, you can choose to specify the second parameter $assoc, which accepts a boolean value. When set to true, the JSON object will be decoded into an associative array. The default is false. Here is an example:
<?php //Store JSON data in a PHP variable $json = '{"Peter":65,"Harry":80,"John":78"Clark":90}'; var_dump(json_decode($json, true)); ?>Test and see‹/›
The output of the above example is as follows:
array(4) { ["Peter"]=> int(65) ["Harry"]=> int(8) ["John"]=> int(78) ["Clark"]=> int(90)}
Now, let's look at an example that will show you how to decode JSON data and access various elements of a JSON object or array in PHP.
<?php //Assign JSON encoded string to PHP variable $json = '{"Peter":65,"Harry":80,"John":78"Clark":90}'; //Decode JSON data into a PHP associative array $arr = json_decode($json, true); //Access values from the associative array echo $arr["Peter"]; //Output: 65 echo $arr["Harry"]; //Output: 80 echo $arr["John"]; //Output: 78 echo $arr["Clark"]; //Output: 90 //Decode JSON data into a PHP object $obj = json_decode($json); //Access values from the returned object echo $obj;->Peter; //Output: 65 echo $obj;->Harry; //Output: 80 echo $obj;->John; //Output: 78 echo $obj;->Clark; //Output: 90 ?>Test and see‹/›
You can also useforeach()Loop through the decoded data as follows:
<?php //Assign JSON encoded string to PHP variable $json = '{"Peter":65,"Harry":80,"John":78"Clark":90}'; //Decode JSON data into a PHP associative array $arr = json_decode($json, true); //Traverse an associative array foreach($arr as $key=>$value){ echo $key . "=>" . $value . "<br>"; } echo "<hr>"; //Decode JSON data into a PHP object $obj = json_decode($json); //Traverse the object foreach($obj as $key => $value){ echo $key . "=>" . $value . "<br>"; } ?>Test and see‹/›
JSON objects and arrays can also be nested. JSON objects can arbitrarily contain other JSON objects, arrays, nested arrays, and arrays of JSON objects, etc. The following example will show you how to decode nested JSON objects and print all their values in PHP.
<?php //Define a recursive function to extract nested values function printValues($arr) { global $count; global $values; //Check if the input is an array if(!is_array($arr)){ die("Error: Input is not an array"); } /* Traverse the array, if the value itself is an array, then make a recursive call The function adds the found values to the output items array And increment the counter for each value found1 */ foreach($arr as $key=>$value){ if(is_array($value)){ printValues($value); } else{ $values[] = $value; $count++; } } // Return the total count and values found in the array return array('total' => $count, 'values' => $values); } //Assign JSON encoded string to PHP variable $json = '{ "book": { "name": "Harry Potter and the Goblet of Fire", "author": "J. K. Rowling", "year": 2000, "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"], "genre": "Fantasy Fiction", "price": { "paperback": "$10.40", "hardcover": "$20.32", "kindle": "4.11" } } }'; //Decode JSON data into PHP associative array format $arr = json_decode($json, true); //Call this function and print all values $result = printValues($arr); echo "<h3>" . $result["total"] . " value(s) found: </h3>"; echo implode("<br>", $result["values"]); echo "<hr>"; //Print a value echo $arr["book"]["author"] . "<br>"; //Output: J. K. Rowling echo $arr["book"]["characters"][0] . "<br>"; //Output: Harry Potter echo $arr["book"]["price"]["hardcover"]; //Output: $20.32 ?>Test and see‹/›