The Language APIs Speak
APIs exchange data as JSON — text like {"id": 1, "name": "Ana"}. PHP translates in both directions with two built-in functions: json_encode turns a value into JSON text, json_decode turns JSON text back into PHP data.
Associative arrays are the natural carrier: the array's keys become the JSON keys, exactly as written. Passing true as the second argument of json_decode asks for arrays back (instead of objects) — the examples here always do.
From Array to JSON
json_encode produces compact JSON for machines; the JSON_PRETTY_PRINT flag produces readable JSON for humans and logs. Dropping empty fields is your call to make: filter them out of the array before encoding.
Encode, compact and pretty
Ana has no email, and the filter removes the empty field from her JSON entirely. Ben's full record prints indented.
Output: PHP script
<?php
function toJson(array $user): string {
// Leave empty fields out of the JSON entirely.
return json_encode(array_filter($user, fn($value) => $value !== ""));
}
$ana = ["id" => 1, "name" => "Ana", "email" => ""];
echo toJson($ana) . "\n";
$ben = ["id" => 2, "name" => "Ben", "email" => "[email protected]"];
echo json_encode($ben, JSON_PRETTY_PRINT) . "\n";
From JSON to Data
json_decode parses JSON into arrays. Unknown JSON keys are not dropped — they ride along as extra entries your code is free to ignore; missing keys are simply absent, so read them with ?? and a default. Bad JSON returns null, and json_last_error_msg() tells you why — always check before trusting the result.
Decode and the extra key
The JSON carries an extra key the code never asked for — no error, it simply appears in the decoded array, as the key list shows. Broken JSON, on the other hand, returns null with a real error message.
Output: PHP script
<?php
$data = '{"id": 7, "name": "Cleo", "extra": "ignored"}';
$user = json_decode($data, true);
echo "id: {$user['id']}, name: {$user['name']}\n";
echo "keys: " . implode(", ", array_keys($user)) . "\n";
$broken = json_decode('{"id": ', true);
if ($broken === null) {
echo "error: " . json_last_error_msg() . "\n";
}
Nested Data
Real API payloads nest: an order carries its user and a list of items. Arrays inside arrays map to JSON automatically — a keyed array becomes a JSON object, a list becomes a JSON array — no special handling needed.
An order with a user inside
The nested user array becomes a nested JSON object, the items list becomes a JSON array — the shape of the PHP data is the shape of the JSON.
Output: PHP script
<?php
$order = [
"id" => 1042,
"items" => ["keyboard", "mouse"],
"user" => ["id" => 1, "name" => "Ana"],
];
echo json_encode($order, JSON_PRETTY_PRINT) . "\n";