← Back to Chapters

PHP json_decode() Function

? PHP json_decode() Function

? Quick Overview

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.

? Key Concepts

  • JSON strings can be decoded into objects or arrays
  • Associative arrays are easier to work with in loops
  • Error handling is essential when decoding JSON

⚙️ Syntax / Theory

? View Code Example
// General syntax of json_decode()
json_decode(string $json, ?bool $associative = null, int $depth = 512, int $options = 0): mixed
  • json: JSON string to decode
  • associative: true for array, false for object
  • depth: Maximum recursion depth
  • options: JSON decoding options

? Code Example 1: Decode to Object

? View Code Example
// 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
?>

?️ Code Example 2: Decode to Associative Array

? View Code Example
// 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
?>

? Code Example 3: Nested JSON

? View Code Example
// 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
?>

✨ Code Example 4: Handling Invalid JSON

? View Code Example
// 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
}
?>

? Live Output / Explanation

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.

? Interactive Understanding

You can modify the JSON string values and instantly observe how PHP objects and arrays change when decoded.

? Use Cases

  • Handling API responses
  • Reading JSON configuration files
  • Processing AJAX responses

✅ Tips & Best Practices

  • Always validate JSON before decoding
  • Use associative arrays for easier iteration
  • Check errors using json_last_error()

? Try It Yourself

  • Decode a JSON list of students and print names
  • Read a JSON file and convert it to a PHP object
  • Loop through nested JSON arrays