The json_decode Function
The json_decode
function converts a string in JSON format into PHP variables. The first parameter of the function accepts a JSON string, the second - a conversion flag (optional), and the third - the recursion depth (optional). By default, the function returns associative arrays.
Syntax
json_decode(string, [assoc = false], [depth = 512], [flags = 0]);
Example
Convert a simple JSON string to a PHP object:
<?php
$json = '{"a":1,"b":2,"c":3}';
$res = json_decode($json);
print_r($res);
?>
Code execution result:
stdClass Object
(
[a] => 1
[b] => 2
[c] => 3
)
Example
Convert a JSON string to an associative array:
<?php
$json = '{"a":1,"b":2,"c":3}';
$res = json_decode($json, true);
print_r($res);
?>
Code execution result:
[
'a' => 1,
'b' => 2,
'c' => 3,
]
Example
Handling invalid JSON:
<?php
$json = '{"a":1,"b":2,"c":3';
$res = json_decode($json);
var_dump($res);
?>
Code execution result:
NULL
See Also
-
the
json_encode
function,
which converts PHP data to JSON -
the
serialize
function,
which converts PHP data to a string