PHP json_decode() Function

PHP json_decode() function is “used to decode a JSON string.” It converts a JSON-encoded string into a PHP variable. It’s the inverse operation of json_encode().

Syntax

json_decode(string $json [, bool $assoc = FALSE 
            [, int $depth = 512 [, int $options = 0 ]]])

Parameters

$json(required): This is the JSON string to be decoded. It only works with UTF-8 encoded strings.

$assoc(optional): It is the boolean type parameter; when set to true, returned, the objects will be converted into associative arrays. When set to false(default), JSON objects will be returned as objects. 

$depth(optional): The integer type parameter specifies the recursion depth.

$options(optional): It is a bitmask of JSON decode options including JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY and JSON_THROW_ON_ERROR.

Return value

This function returns the encoded JSON value in the appropriate PHP type.

Visual Representation of Specifying the assoc argumentVisual Representation of PHP json_decode() Function

Example 1: How to Use json_decode() Function

<?php

$json = '{
 "name": "David",
 "age": 32,
 "country": "USA"}';

// Decode JSON string to PHP object 
print_r(json_decode($json));

Output

stdClass Object
(
 [name] => David
 [age] => 32
 [country] => USA
)

Example 2: Specifying the assoc argumentVisual Representation of Specifying the assoc argument

<?php

$json = '{
 "name": "David",
 "age": 32,
 "country": "USA"}';
 
// Decode JSON string to associative array 
print_r(json_decode($json,true));

Output

Array
(
 [name] => David
 [age] => 32
 [country] => USA
)

Example 3: Accessing values from PHP object

<?php

$json = '{
"name": "David",
"age": 32,
"country": "USA"}';

$obj = json_decode($json);

echo $obj->name."\n";
echo $obj->age."\n";
echo $obj->country;

Output

David
32
USA

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.