Syntax
mixed json_decode( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
The json_decode() function can take a JSON encoded string and convert into a PHP variable.
The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.
Example 1
$jsonData= '[
{"name":"Raja", "city":"Hyderabad", "state":"Telangana"},
{"name":"Adithya", "city":"Pune", "state":"Maharastra"},
{"name":"Jai", "city":"Secunderabad", "state":"Telangana"}
$people= json_decode($jsonData, true);
$count= count($people);
// Access any person who lives in Telangana
for ($i=0; $i < $count; $i++) {
if($people[$i]["state"] == "Telangana") {
echo $people[$i]["name"] . "\n";
echo $people[$i]["city"] . "\n";
echo $people[$i]["state"] . "\n\n";
Output
Hyderabad
Telangana
Secunderabad
Telangana
Example 2
// Assign a JSON object to a variable
$someJSON = '{"name" : "Raja", "Adithya" : "Jai"}';
// Convert the JSON to an associative array
$someArray = json_decode($someJSON, true);
// Read the elements of the associative array
foreach($someArray as $key => $value) {
echo "[" . $key . "][" . $value . "]";
Output
[name][Raja][Adithya][Jai]
php_function_reference.htm
Kickstart Your
Career
Get certified by completing the course
Get Started