PHP JSON
PHP JSON functions convert data between PHP arrays or objects and JSON text. JSON is the standard format for APIs and JavaScript front ends, so you will use json_encode and json_decode constantly.
Encoding PHP Arrays to JSON
Associative arrays become JSON objects; lists become JSON arrays.
<?php
$post = [
'id' => 7,
'title' => 'Hello JSON',
'tags' => ['php', 'api'],
'published' => true,
];
echo json_encode($post), "\n";
echo json_encode([1, 2, 3]);{"id":7,"title":"Hello JSON","tags":["php","api"],"published":true}
[1,2,3]Pretty Printing JSON
<?php
echo json_encode(['name' => 'Café', 'url' => 'https://x.com/a'],
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);{
"name": "Café",
"url": "https://x.com/a"
}Decoding JSON in PHP
json_decode() returns objects by default. Pass true as the second argument to get associative arrays, which most developers prefer.
<?php
$json = '{"user":{"name":"Faisal","skills":["php","sql"]}}';
$obj = json_decode($json);
echo $obj->user->name, "\n";
$arr = json_decode($json, true);
echo $arr['user']['skills'][1];Faisal sql
Handling JSON Errors
Invalid JSON makes json_decode return null. Use the JSON_THROW_ON_ERROR flag to get an exception you can catch.
<?php
try {
json_decode('{bad json}', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "Invalid JSON: " . $e->getMessage();
}Invalid JSON: Syntax error
Returning a JSON API Response
To build a tiny API endpoint, set the content type header and echo the encoded data. Frameworks like Laravel do this for you when you return an array.
<?php
header('Content-Type: application/json');
http_response_code(200);
echo json_encode(['status' => 'ok', 'time' => date('c')]);{"status":"ok","time":"2026-10-31T10:00:00+00:00"}Frequently asked questions
How do I convert JSON to an array in PHP?
Call json_decode($json, true). The true flag returns associative arrays instead of stdClass objects.
Why does json_encode return false?
Usually because of invalid UTF-8 text or unsupported values like resources. Use JSON_THROW_ON_ERROR to see the exact reason.
How do I stop json_encode escaping slashes?
Add the JSON_UNESCAPED_SLASHES flag, and JSON_UNESCAPED_UNICODE to keep non-English characters readable.