📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners JSON Handling

JSON Handling

5 min read Quiz at the end
json_encode() converts PHP data to a JSON string and json_decode() parses JSON back to PHP. Pass true as the second argument to get an associative array. JSON is the standard format for APIs and data exchange.

JSON in PHP

// Encode PHP to JSON
$user = ["name" => "Alice", "age" => 28, "active" => true];
$json = json_encode($user);
// {"name":"Alice","age":28,"active":true}

// Pretty print
$pretty = json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// Decode JSON to PHP
$data = json_decode($json, true);  // true = associative array
echo $data["name"];  // Alice

$obj = json_decode($json);         // false = stdClass object
echo $obj->name;     // Alice

// Error handling
$result = json_decode("invalid json", true);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_last_error_msg();
}

// PHP 8.3 — json_validate()
json_validate($json);  // true/false
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which function encodes PHP to JSON?
💡 json_encode($data) converts PHP arrays/objects to a JSON string.
2. Which function decodes JSON to PHP?
💡 json_decode($json, true) returns an associative array; false returns stdClass.
3. Passing true as second argument to json_decode() returns:
💡 json_decode($json, true) returns an associative array instead of stdClass.
4. Which flag pretty-prints JSON output?
💡 JSON_PRETTY_PRINT formats JSON with indentation for readability.
5. How do you check for JSON encoding errors?
💡 json_last_error() returns the last JSON error code; use JSON_THROW_ON_ERROR in PHP 7.3+.