jsondecode.com logo

HomeChevronBlogChevronJSON in PHP: Complete Guide

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.

author

Shashank Jain

Author

14/06/20261 minute 12 seconds read
JSON in PHP: Complete GuideJSON in PHP: Complete Guide

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

PitfallCauseFix
null returnedNon-UTF-8 stringsUse mb_convert_encoding() or JSON_INVALID_UTF8_SUBSTITUTE
Floats lose precisionPHP float serializationUse JSON_PRESERVE_ZERO_FRACTION
Empty array becomes {}Associative array detectionUse array_values() to reindex
Unicode escapingDefault encodes non-ASCIIAdd 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

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.