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.