PHP JSON

JSON is how PHP talks to JavaScript, mobile apps, and other APIs.

Encoding

PHP
<?php
$data = [
    'name'   => 'Sita',
    'marks'  => [88, 74, 91],
    'active' => true,
];

echo json_encode($data);
// {"name":"Sita","marks":[88,74,91],"active":true}

echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

JSON_UNESCAPED_UNICODE matters for Devanagari — without it, "नेपाल" becomes a wall of ने... escapes. Valid, but unreadable.

Decoding

PHP
<?php
$json = '{"name":"Sita","marks":[88,74]}';

$arr = json_decode($json, true);   // associative array
echo $arr['name'];

$obj = json_decode($json);          // stdClass object
echo $obj->name;

Pass true as the second argument unless you specifically want objects — arrays are easier to work with in most PHP code.

Always check for failure

json_decode() returns null on invalid JSON, which is indistinguishable from the valid JSON "null". Use the exception flag:

PHP
<?php
try {
    $arr = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "Invalid JSON: " . $e->getMessage();
}

Returning JSON from a PHP endpoint

PHP
<?php
header('Content-Type: application/json; charset=utf-8');

echo json_encode([
    'ok'   => true,
    'data' => $products,
], JSON_UNESCAPED_UNICODE);
exit;

Set the header before any output, and exit afterwards so no stray HTML corrupts the response.

Reading a JSON request body

Form posts arrive in $_POST, but a JavaScript fetch() sending JSON does not — read the raw body instead:

PHP
<?php
$raw  = file_get_contents('php://input');
$body = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);

$email = $body['email'] ?? '';