JSON (JavaScript Object Notation) is the universal lightweight data interchange format for RESTful APIs and modern web applications. PHP provides native functions json_encode() and json_decode() to convert between PHP arrays/objects and JSON strings.
flowchart LR
A["PHP Array / Object"] -->|json_encode()| B["JSON Format String"]
B -->|json_decode($json, true)| C["PHP Associative Array"]
B -->|json_decode($json, false)| D["PHP stdClass Object"]
json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)json_decode($json, assoc: true, flags: JSON_THROW_ON_ERROR)<?php
declare(strict_types=1);
// 1. Encoding PHP Associative Array to JSON String
$responsePayload = [
'status' => 'success',
'code' => 200,
'data' => [
'user_id' => 101,
'username' => 'maksudur',
'roles' => ['admin', 'developer']
]
];
try {
$jsonString = json_encode($responsePayload, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
echo "--- Encoded JSON Output ---
" . $jsonString . "
";
// 2. Decoding JSON String back to Associative Array
$decodedArray = json_decode($jsonString, true, 512, JSON_THROW_ON_ERROR);
echo "Decoded User ID: " . $decodedArray['data']['user_id'] . "
";
echo "Decoded Username: " . $decodedArray['data']['username'] . "
";
} catch (JsonException $e) {
echo "JSON Processing Error: " . $e->getMessage() . "
";
}
JSON_THROW_ON_ERROR in PHP 7.3+: Throws a catchable JsonException instead of requiring manual json_last_error() checks.true to json_decode(): json_decode($json, true) decodes objects into PHP associative arrays instead of stdClass instances.JSON_PRETTY_PRINT for Debugging & API Dumps: Makes JSON formatted and human-readable during testing.Write a line of code using json_encode() with JSON_THROW_ON_ERROR that converts an associative array $data into a JSON string!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.