SyntaxStudy
Sign Up
PHP Beginner 3 min read

JSON Responses

JSON Responses

Always set Content-Type: application/json, use json_encode(), and return appropriate HTTP status codes.

Example
function jsonResponse(mixed $data, int $status = 200, array $meta = []): void {
    http_response_code($status);
    header("Content-Type: application/json");
    $payload = ["data" => $data];
    if ($meta) $payload["meta"] = $meta;
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
    exit();
}
jsonResponse($users, 200, ["total" => count($users), "page" => 1]);
jsonResponse(["message" => "Created"], 201);
jsonResponse(["error" => "Not found"], 404);
Pro Tip

JSON_THROW_ON_ERROR causes json_encode to throw on encoding failures instead of returning false silently.