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