Returning JSON from a PHP Script

前端 未结 18 1408
南方客
南方客 2020-11-21 04:59

I want to return JSON from a PHP script.

Do I just echo the result? Do I have to set the Content-Type header?

18条回答
  •  一生所求
    2020-11-21 05:47

    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:

     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.

提交回复
热议问题