JSON Encode/Decode
On this page
Encoding Arrays to JSON
json_encode converts arrays/objects into JSON strings. This is the basis for API responses.
<?php
$data = [
'ok' => true,
'items' => [
['id' => 1, 'title' => 'PHP Intro'],
['id' => 2, 'title' => 'Arrays'],
],
];
echo json_encode($data);
Pretty Print (Development)
Pretty JSON is easier to read while developing. For production, compact JSON is usually fine.
<?php echo json_encode($data, JSON_PRETTY_PRINT);
Decoding JSON to Arrays
json_decode can return an object or an associative array. For typical backend code, associative arrays are often easier to work with.
<?php
$raw = '{"id":1,"name":"Ozan"}';
$decoded = json_decode($raw, true); // true => associative array
echo $decoded['name'];
Handling JSON Errors
Invalid JSON returns null. Always check json_last_error or use the JSON_THROW_ON_ERROR flag to avoid silent failures.
<?php
try {
$payload = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo 'Invalid JSON';
}
Returning JSON Responses
For APIs, set the correct content type and return JSON. Never echo raw errors in production.
<?php
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => true,
'message' => 'Hello',
]);
Production Tip
Validate decoded payloads (required keys, types) before using them. JSON decode gives you “some data”, not “trusted data”. Validation belongs on the server.