JSON, which stands for JavaScript Object Notation, is a syntax for storing and exchanging data.
Being a text-based format, JSON can be easily transmitted to and from a server and utilized as a data format by any programming language.
PHP provides built-in functions for handling JSON.
The primary functions are:
The json_encode()
function is used to convert a value into JSON format.
This example demonstrates how to encode an associative array into a JSON object:
<?php $age = array(“Peter”=>35, “Ben”=>37, “Joe”=>43); echo json_encode($age); ?> |
This example illustrates how to encode an indexed array into a JSON array:
<?php $cars = array(“Volvo”, “BMW”, “Toyota”); echo json_encode($cars); ?> |
The json_decode()
function is used to convert a JSON object into a PHP object or an associative array.
This example shows how to decode JSON data into a PHP object:
<?php $jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’; var_dump(json_decode($jsonobj)); ?> |
By default, the json_decode() function returns an object. However, if you set the second parameter to true, JSON objects will be decoded into associative arrays.
This example demonstrates how to decode JSON data into a PHP associative array:
<?php e”:43}’; |
Here are two examples of how to access the decoded values from both an object and an associative array:
This example demonstrates how to access values from a PHP object:
<?php $jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’; $obj = json_decode($jsonobj); echo $obj->Peter; echo $obj->Ben; echo $obj->Joe; ?> |
This example illustrates how to access values from a PHP associative array:
<?php $jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’; $arr = json_decode($jsonobj, true); echo $arr[“Peter”]; echo $arr[“Ben”]; echo $arr[“Joe”]; ?> |
You can also iterate through the values using a foreach()
loop:
This example demonstrates how to loop through the values of a PHP object:
<?php $jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’; $obj = json_decode($jsonobj); foreach($obj as $key => $value) { echo $key . ” => “ . $value . “<br>”; } ?> |
This example illustrates how to loop through the values of a PHP associative array:
<?php $jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’; $arr = json_decode($jsonobj, true); foreach($arr as $key => $value) { echo $key . ” => “ . $value . “<br>”; } ?> |