PHP json_encode() and json_decode() Functions
JSON is a common format for APIs and configuration exchange. PHP provides json_encode() and json_decode() to convert between PHP values and JSON text.
Encode a PHP Value
$data = [
"name" => "Ava",
"active" => true,
"roles" => ["author", "editor"],
];
$json = json_encode(
$data,
JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
);
JSON_THROW_ON_ERROR makes encoding failures raise a JsonException, which can be handled explicitly.
Decode JSON
try {
$data = json_decode(
$json,
true,
512,
JSON_THROW_ON_ERROR
);
} catch (JsonException $exception) {
// Handle invalid JSON without exposing internal details.
}
Passing true as the second argument returns objects as associative arrays. Omit it when object results are preferred.
Validate the Result
Successful decoding does not guarantee the data has the shape your application expects. Check required keys, types, lengths, and allowed values before using the decoded data.
Summary
Use json_encode() to produce JSON and json_decode() to parse it. Handle encoding errors and validate decoded data before trusting it.