How do I work with JSON in PHP?
Use json_encode($data) and json_decode($json, true). Pass JSON_THROW_ON_ERROR so malformed input raises an exception instead of returning null.
$data = ['title' => 'Intro to Python', 'views' => 197];
$json = json_encode($data, JSON_THROW_ON_ERROR);
// {"title":"Intro to Python","views":197}
$back = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
// ['title' => 'Intro to Python', 'views' => 197]#The second argument to json_decode
true returns associative arrays. Omit it and you get stdClass objects, accessed with -> instead of []. Arrays are usually easier to work with in PHP; pick one and be consistent.
#Useful flags
json_encode($data,
JSON_PRETTY_PRINT | // readable output
JSON_UNESCAPED_SLASHES | // / instead of \/
JSON_UNESCAPED_UNICODE | // é instead of \u00e9
JSON_THROW_ON_ERROR
);Without JSON_THROW_ON_ERROR, both functions return null on failure — and null is also the valid decoding of the input "null". That ambiguity is how JSON bugs hide.
#Sequential arrays vs objects
json_encode([1, 2, 3]); // [1,2,3] — a JSON array
json_encode([1 => 'a', 2 => 'b']); // {"1":"a",...} — a JSON objectPHP emits an array only when the keys are 0..n with no gaps. This is why array_filter results often serialise as objects — the keys have holes. Wrap them in array_values().
#Returning JSON from an endpoint
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_THROW_ON_ERROR);
exit;#Reading a JSON request body
$body = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);$_POST is only populated for form encodings. A JSON request body has to be read from the raw input stream.