Languages Knowledge Base

Working with JSON in PHP: json_encode & json_decode

Complete PHP JSON guide: json_encode() with JSON_PRETTY_PRINT, json_decode() into associative arrays, JSON_THROW_ON_ERROR, and PHP 8 best practices.

In PHP, use json_decode($text, true) to parse a JSON string into an associative array and json_encode($array, JSON_PRETTY_PRINT) to produce formatted JSON output. Both functions are built into PHP 5.2+.

Native JSON Support in PHP

PHP has built-in JSON functions since PHP 5.2, with important improvements in PHP 7.3+ (JSON_THROW_ON_ERROR) and PHP 8.

Core Functions:

  • json_decode($json, true) — Parse JSON to associative array (true) or stdClass object (false/null).
  • json_encode($value, JSON_PRETTY_PRINT) — Serialize PHP value to JSON string.
  • json_last_error() — Returns last JSON error code (legacy error checking).
json
<?php

// Parse JSON to associative array
$json = '{"name":"Alice","score":99,"active":true}';
$data = json_decode($json, true); // true = assoc array
echo $data['name']; // Alice

// Serialize PHP array to JSON
$arr = ['name' => 'Bob', 'score' => 85];
echo json_encode($arr);
// {"name":"Bob","score":85}

// Pretty print JSON
echo json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// PHP 7.3+ — Throw exception on error
try {
    $data = json_decode($invalidJson, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "JSON error: " . $e->getMessage();
}

Try the free JSON Formatter

Runs entirely in your browser — no upload, no signup, and your data never leaves your device.

Open JSON Formatter

Frequently Asked Questions

How do I pretty print JSON in PHP?

Pass JSON_PRETTY_PRINT as the second argument to json_encode(): json_encode($data, JSON_PRETTY_PRINT).

Should json_decode return an array or an object in PHP?

Pass true as the second argument to get an associative array. Without it, PHP returns a stdClass object.

How do I handle JSON errors in PHP 7.3+?

Pass JSON_THROW_ON_ERROR as the flags argument and catch \JsonException.

Related JSON Topics & Reference Articles