Open In App

PHP | json_decode() Function

The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable.

Syntax:



json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )

Parameters: This function accepts four parameters as mentioned above and described below:

Return values: This function returns the encoded JSON value in appropriate PHP type. If the json cannot be decoded or if the encoded data is deeper than the recursion limit then it returns NULL.



Below examples illustrate the use of json_decode() function in PHP:
Example 1:




<?php
  
// Declare a json string
$json = '{"g":7, "e":5, "e":5, "k":11, "s":19}';
  
// Use json_decode() function to
// decode a string
var_dump(json_decode($json));
  
var_dump(json_decode($json, true));
  
?>

Output:
object(stdClass)#1 (4) {
  ["g"]=>
  int(7)
  ["e"]=>
  int(5)
  ["k"]=>
  int(11)
  ["s"]=>
  int(19)
}
array(4) {
  ["g"]=>
  int(7)
  ["e"]=>
  int(5)
  ["k"]=>
  int(11)
  ["s"]=>
  int(19)
}

Example 2:




<?php
  
// Declare a json string
$json = '{"geeks": 7551119}';
  
// Use json_decode() function to
// decode a string
$obj = json_decode($json);
  
// Display the value of json object
print $obj->{'geeks'};
  
?>

Output:
7551119

Common Errors while using json_decode() function:

Reference: http://php.net/manual/en/function.json-decode.php


Article Tags :