The json_decode() function in PHP converts a JSON formatted string into a PHP variable such as an object or an associative array. It is widely used when working with APIs, configuration files, or JSON-based data exchange.
// General syntax of json_decode()
json_decode(string $json, ?bool $associative = null, int $depth = 512, int $options = 0): mixed
// Decoding JSON into a PHP object
<?php
$json = '{"name":"John","age":30,"city":"New York"}';
$obj = json_decode($json);
echo $obj->name; // Output: John
echo $obj->age; // Output: 30
?>
// Decoding JSON into an associative array
<?php
$json = '{"name":"Alice","age":25,"city":"London"}';
$array = json_decode($json, true);
echo $array["name"]; // Output: Alice
echo $array["city"]; // Output: London
?>
// Accessing nested JSON values
<?php
$json = '{"id":1,"product":"Laptop","specs":{"brand":"Dell","ram":"16GB","storage":"512GB SSD"}}';
$data = json_decode($json, true);
echo $data["product"]; // Output: Laptop
echo $data["specs"]["brand"]; // Output: Dell
?>
// Checking JSON decoding errors
<?php
$json = "{name:John, age:30}"; // Invalid JSON (missing quotes)
$result = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "Error: " . json_last_error_msg(); // Output: Syntax error
}
?>
Each example demonstrates how JSON data is transformed into usable PHP structures. Error handling ensures the application does not break when invalid JSON is encountered.
You can modify the JSON string values and instantly observe how PHP objects and arrays change when decoded.
json_last_error()