Encoding and Decoding JSON in PHP

JSON has become the default data interchange format for APIs, and PHP’s json_encode/json_decode functions handle it natively — but a few option flags matter more than most developers realize.

$data = ['name' => 'Widget', 'price' => 19.99, 'tags' => ['new', 'sale']];

$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;

// Decode as an associative array (recommended) instead of stdClass objects
$decoded = json_decode($json, true);
echo $decoded['name'];

// Always check for decode errors on untrusted input
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('Invalid JSON: ' . json_last_error_msg());
}

The Common Gotcha: UTF-8

json_encode fails silently (returns false) on invalid UTF-8 input by default — a frequent cause of “why is my API returning nothing” bugs when data from a legacy database uses a different encoding. Passing JSON_INVALID_UTF8_SUBSTITUTE or fixing the source encoding resolves it.