PHP Code Examples

Return a JSON Response from PHP

Set the correct response headers, encode structured data, and return suitable HTTP status codes from a PHP endpoint.

Example

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

$data = [
    'success' => true,
    'message' => 'Request completed.',
    'items' => [
        ['id' => 1, 'name' => 'Example'],
    ],
];

$json = json_encode(
    $data,
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);

if ($json === false) {
    http_response_code(500);
    echo '{"success":false,"message":"JSON encoding failed."}';
    exit;
}

echo $json;

Explanation

A JSON endpoint should return JSON consistently, including for errors. Set the content type before sending output and avoid notices or HTML warnings in the response.

For APIs, validate inputs, authenticate protected operations, and use meaningful HTTP status codes.

Share this page Help other developers discover this resource.