According to the manual on json_encode
the method can return a non-string (false):
Returns a JSON encoded string on success or FALSE
on failure.
When this happens echo json_encode($data)
will output the empty string, which is invalid JSON.
json_encode
will for instance fail (and return false
) if its argument contains a non UTF-8 string.
This error condition should be captured in PHP, for example like this:
<?php header("Content-Type: application/json"); // Collect what you need in the $data variable. $json = json_encode($data); if ($json === false) { // Avoid echo of empty string (which is invalid JSON), and // JSONify the error message instead: $json = json_encode(["jsonError" => json_last_error_msg()]); if ($json === false) { // This should not happen, but we go all the way now: $json = '{"jsonError":"unknown"}'; } // Set HTTP response status code to: 500 - Internal Server Error http_response_code(500); } echo $json; ?>
Then the receiving end should of course be aware that the presence of the jsonError property indicates an error condition, which it should treat accordingly.
In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation.
Read more about dealing with JSON errors in PHP's Documentation.