JSON & APIs in PHP
From the PHP cheat sheet · Web Features · verified Jul 2026
JSON & APIs
Working with JSON and building APIs
php
// JSON encoding
$json = json_encode($data);
$json = json_encode($data, JSON_PRETTY_PRINT);
// JSON decoding
$data = json_decode($json); // Object
$array = json_decode($json, true); // Array
// API response
header('Content-Type: application/json');
echo json_encode(['status' => 'success']);
// Handle JSON input
$input = json_decode(file_get_contents('php://input'), true);💡 Always validate JSON with json_last_error()
⚡ Use php://input for raw POST data
📌 Set proper Content-Type and status codes
🔥 json_validate() in PHP 8.3+ checks without decoding