PHP's built-in JSON functions make serialising and deserialising data straightforward.
$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);
$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
$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());
}
$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