PHP JSON

PHP JSON

JSON (JavaScript Object Notation) is the standard data exchange format for web APIs. PHP's json_encode() and json_decode() make it trivial to work with.

1 - PHP Array → JSON

$user = [
    "id"    => 1,
    "name"  => "Alice",
    "roles" => ["admin", "editor"],
    "meta"  => ["active" => true]
];

echo json_encode($user);
// {"id":1,"name":"Alice","roles":["admin","editor"],"meta":{"active":true}}

echo json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

2 - JSON → PHP

$json = '{"id":1,"name":"Alice","active":true}';

// As associative array (recommended)
$data = json_decode($json, true);
echo $data["name"]; // Alice

// As object
$obj = json_decode($json);
echo $obj->name; // Alice

3 - API Response Pattern

header("Content-Type: application/json; charset=utf-8");

echo json_encode([
    "status"  => "success",
    "message" => "User created",
    "data"    => ["id" => 42, "name" => "Alice"]
]);

4 - Error Checking

$data = json_decode($untrustedInput, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    throw new InvalidArgumentException(
        "Invalid JSON: " . json_last_error_msg()
    );
}

Note: Always pass JSON_THROW_ON_ERROR as a flag in PHP 7.3+ to have json_encode()/json_decode() throw a JsonException instead of silently returning null on failure.

-Tip-