JSON is the standard format for exchanging data between a PHP backend and a frontend, or between two servers — nearly every API request and response uses it. PHP has JSON support built in, no package required.
$user = [
'name' => 'Sam',
'age' => 28,
'active' => true,
];
echo json_encode($user);
// {"name":"Sam","age":28,"active":true}echo json_encode($user, JSON_PRETTY_PRINT);By default, this returns an stdClass object — pass true as the second argument to get an associative array instead, usually the more convenient choice.
$json = '{"name":"Sam","age":28}';
$object = json_decode($json);
echo $object->name; // Sam — object access
$array = json_decode($json, true);
echo $array['name']; // Sam — array accessheader('Content-Type: application/json');
$users = getUsersFromDatabase(); // an array of associative arrays
echo json_encode([
'success' => true,
'data' => $users,
]);Invalid JSON makes json_decode() return null — worth checking explicitly, since a genuinely empty result also decodes to something falsy.
$data = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
die('Invalid JSON: ' . json_last_error_msg());
}What json_encode() can't do
Not every PHP value converts cleanly — a resource (like an open file handle) can't be represented in JSON at all, and encoding one silently produces 0 rather than an error.