Working with JSON in PHP

PHP has built-in support for JSON through the json_encode() and json_decode() functions. This guide covers everything you need to know about working with JSON in PHP.

Decoding JSON

Use json_decode() to parse a JSON string:

name;  // John
echo $data->age;   // 30

// Parse JSON string to associative array
$data = json_decode($json, true);
echo $data['name'];  // John
echo $data['age'];   // 30

// Parse JSON array
$jsonArray = '[1, 2, 3, "four", true, null]';
$items = json_decode($jsonArray, true);
print_r($items);  // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => four [4] => 1 [5] => )

// With depth and flags
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
?>

Encoding to JSON

Use json_encode() to convert PHP values to JSON:

 'Jane',
    'age' => 25,
    'isActive' => true,
    'hobbies' => ['reading', 'coding'],
    'address' => null
];

// Basic encoding
$json = json_encode($user);
echo $json;
// {"name":"Jane","age":25,"isActive":true,"hobbies":["reading","coding"],"address":null}

// Pretty print
$prettyJson = json_encode($user, JSON_PRETTY_PRINT);
echo $prettyJson;
/*
{
    "name": "Jane",
    "age": 25,
    "isActive": true,
    "hobbies": [
        "reading",
        "coding"
    ],
    "address": null
}
*/

// Multiple flags
$json = json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?>

JSON Encoding Flags

 'https://example.com/path',
    'html' => '
Hello
', 'unicode' => 'Привет мир', 'number' => '123' ]; // JSON_UNESCAPED_SLASHES - Don't escape / echo json_encode(['url' => 'http://example.com'], JSON_UNESCAPED_SLASHES); // {"url":"http://example.com"} // JSON_UNESCAPED_UNICODE - Don't escape Unicode characters echo json_encode(['text' => 'Привет'], JSON_UNESCAPED_UNICODE); // {"text":"Привет"} // JSON_NUMERIC_CHECK - Encode numeric strings as numbers echo json_encode(['id' => '123'], JSON_NUMERIC_CHECK); // {"id":123} // JSON_FORCE_OBJECT - Force array to object echo json_encode([1, 2, 3], JSON_FORCE_OBJECT); // {"0":1,"1":2,"2":3} // JSON_PRESERVE_ZERO_FRACTION - Preserve .0 in floats echo json_encode(10.0, JSON_PRESERVE_ZERO_FRACTION); // 10.0 ?>

Error Handling

getMessage();
    echo 'Line: ' . $e->getLine();
}

// Helper function for validation
function isValidJson(string $json): bool {
    json_decode($json);
    return json_last_error() === JSON_ERROR_NONE;
}

// Detailed validation
function validateJson(string $json): array {
    $data = json_decode($json);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'valid' => false,
            'error' => json_last_error_msg(),
            'error_code' => json_last_error()
        ];
    }

    return [
        'valid' => true,
        'data' => $data,
        'type' => gettype($data)
    ];
}

print_r(validateJson('{"name": "John"}'));
// Array ( [valid] => 1 [data] => stdClass Object [type] => object )
?>

Working with JSON Files

 'John', 'age' => 30];
file_put_contents('output.json', json_encode($user, JSON_PRETTY_PRINT));

// Read with error handling
function readJsonFile(string $path): ?array {
    if (!file_exists($path)) {
        throw new RuntimeException("File not found: $path");
    }

    $json = file_get_contents($path);
    $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

    return $data;
}

// Atomic write (prevents corruption)
function writeJsonFile(string $path, $data): void {
    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
    $tempPath = $path . '.tmp';

    file_put_contents($tempPath, $json, LOCK_EX);
    rename($tempPath, $path);
}
?>

API Requests with JSON

 true,
        CURLOPT_HTTPHEADER => ['Accept: application/json'],
        CURLOPT_TIMEOUT => 30
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        throw new RuntimeException("HTTP Error: $httpCode");
    }

    return json_decode($response, true, 512, JSON_THROW_ON_ERROR);
}

// POST JSON data
function postJson(string $url, array $data): array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Accept: application/json'
        ]
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true, 512, JSON_THROW_ON_ERROR);
}

// Using file_get_contents (simpler but less flexible)
$json = file_get_contents('https://api.example.com/data');
$data = json_decode($json, true);
?>

JSON Response in API

 'success', 'data' => $result]);
exit;

// Better JSON response function
function jsonResponse($data, int $statusCode = 200): never {
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
    exit;
}

// Usage
jsonResponse(['user' => ['name' => 'John']], 200);

// Error response
jsonResponse([
    'error' => true,
    'message' => 'User not found'
], 404);

// Reading JSON request body
$input = json_decode(file_get_contents('php://input'), true);
if ($input === null && json_last_error() !== JSON_ERROR_NONE) {
    jsonResponse(['error' => 'Invalid JSON'], 400);
}
?>

Working with Objects

name = $name;
        $this->age = $age;
        $this->password = $password;
    }

    public function jsonSerialize(): array {
        // Exclude password from JSON output
        return [
            'name' => $this->name,
            'age' => $this->age
        ];
    }
}

$user = new User('John', 30, 'secret123');
echo json_encode($user);
// {"name":"John","age":30}

// Convert JSON to object
class UserDto {
    public string $name;
    public int $age;

    public static function fromJson(string $json): self {
        $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

        $user = new self();
        $user->name = $data['name'] ?? '';
        $user->age = $data['age'] ?? 0;

        return $user;
    }
}
?>

JSON Path (jmespath)

 `26`]', $data);
// [{"name": "John", "age": 30}]

// Get first user's name
$firstName = JmesPath::search('users[0].name', $data);
// 'John'
?>

Best Practices