Blog post
JSON in PHP: Complete Guide
Work with JSON in PHP — json_encode, json_decode, error handling, API requests, and common pitfalls with examples.
Shashank Jain
Author


Article
json_decode and json_encode
PHP has built-in JSON functions available since PHP 5.2:
<?php
$json = '{"name": "Alice", "age": 30}';
// Decode to object
$obj = json_decode($json);
echo $obj->name; // Alice
// Decode to associative array
$arr = json_decode($json, true);
echo $arr['name']; // Alice
// Encode PHP to JSON
$data = ['name' => 'Bob', 'scores' => [95, 87]];
echo json_encode($data);
// {"name":"Bob","scores":[95,87]}
?>json_encode Options
<?php
// Pretty print + unescaped slashes
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
// Throw exception on error (PHP 7.3+)
echo json_encode($data, JSON_THROW_ON_ERROR);
?>Error Handling (PHP 7.3+)
<?php
try {
$result = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo 'JSON error: ' . $e->getMessage();
}
?>JSON API Response in PHP
<?php
header('Content-Type: application/json');
$users = [['id' => 1, 'name' => 'Alice']];
echo json_encode(['data' => $users, 'meta' => ['total' => 1]], JSON_PRETTY_PRINT);
?>Common json_encode Pitfalls
| Pitfall | Cause | Fix |
|---|---|---|
| null returned | Non-UTF-8 strings | Use mb_convert_encoding() or JSON_INVALID_UTF8_SUBSTITUTE |
| Floats lose precision | PHP float serialization | Use JSON_PRESERVE_ZERO_FRACTION |
| Empty array becomes {} | Associative array detection | Use array_values() to reindex |
| Unicode escaping | Default encodes non-ASCII | Add JSON_UNESCAPED_UNICODE flag |
FAQ
When should I decode to array vs object?
Use associative arrays (second param true) for most cases — array syntax is simpler in PHP and avoids unexpected behavior with numeric keys.
How do I handle deeply nested JSON?
json_decode has a depth parameter (default 512). For very deep JSON: json_decode($json, true, 1024).
How do I send a JSON POST request in PHP?
Use cURL with CURLOPT_POSTFIELDS set to the JSON string and Content-Type: application/json header. Or use Guzzle: $client->post('/api', ['json' => $data]).
What PHP version should I use for JSON?
PHP 8.0+ for best performance. PHP 7.3+ for JSON_THROW_ON_ERROR. Avoid PHP 5.x.
Does PHP json_decode support JSON with comments?
No. Strip comments first using a JSONC parser, then decode with json_decode.
Keep reading
Recent blogs

Jun 14, 2026
JSON in C#: System.Text.Json and Newtonsoft Complete Guide
Serialize and deserialize JSON in C# using System.Text.Json and Newtonsoft.Json with practical examples.

Jun 14, 2026
JSON to Markdown Table: Convert JSON Arrays Instantly
Convert JSON arrays to Markdown tables in JavaScript, Python, and with the free online tool.

Jun 14, 2026
JSON in TypeScript: Type-Safe Parsing and Validation
Stop using any for JSON in TypeScript — use Zod, type guards, and generics for fully type-safe parsing.