How to Parse JSON in PHP
PHP has built-in json_decode and json_encode functions. Decode to associative arrays or stdClass objects, and encode with formatting flags.
Decode a JSON string
Pass true as the second argument to get an associative array instead of objects.
php
$text = '{"name":"Ada","roles":["admin","dev"]}';
$data = json_decode($text, true);
echo $data["name"]; // Ada
echo $data["roles"][0]; // adminEncode to JSON
Use JSON_PRETTY_PRINT for readable output and JSON_UNESCAPED_UNICODE/SLASHES to keep text clean.
php
$obj = ["name" => "Ada", "active" => true];
echo json_encode($obj);
echo json_encode($obj,
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);Detect decode errors
json_decode returns null on failure; check json_last_error, or pass JSON_THROW_ON_ERROR (PHP 7.3+) to get an exception.
php
try {
$data = json_decode($text, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "Invalid JSON: " . $e->getMessage();
}