How to Work with JSON in PHP

How to Work with JSON in PHP

How to Work with JSON in PHP

PHP's built-in JSON functions make serialising and deserialising data straightforward.

Step 1 — Encode PHP to JSON

$data = [
    'name'    => 'Alice',
    'age'     => 30,
    'active'  => true,
    'scores'  => [95, 87, 92],
    'address' => ['city' => 'Paris', 'zip' => '75001'],
];

$json = json_encode($data);
// {"name":"Alice","age":30,"active":true,...}

// Pretty print for debugging
$pretty = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

Step 2 — Decode JSON to PHP

$json = '{"name":"Alice","age":30,"scores":[95,87,92]}';

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

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

Step 3 — Always Check for Errors

$result = json_decode($untrustedInput, true);

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

// PHP 7.3+ — use JSON_THROW_ON_ERROR flag instead
try {
    $result = json_decode($untrustedInput, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
    throw new \InvalidArgumentException('Invalid JSON: ' . $e->getMessage());
}

Step 4 — Read JSON from an API

$response = file_get_contents('https://api.example.com/users');
$users    = json_decode($response, true, 512, JSON_THROW_ON_ERROR);

foreach ($users as $user) {
    echo $user['name'] . PHP_EOL;
}
All Comments