Returning JSON from a PHP Script

前端 未结 18 1441
南方客
南方客 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:35

    This question got many answers but none cover the entire process to return clean JSON with everything required to prevent the JSON response to be malformed.

    
    /*
     * returnJsonHttpResponse
     * @param $success: Boolean
     * @param $data: Object or Array
     */
    function returnJsonHttpResponse($success, $data)
    {
        // remove any string that could create an invalid JSON 
        // such as PHP Notice, Warning, logs...
        ob_clean();
    
        // this will clean up any previously added headers, to start clean
        header_remove(); 
    
        // Set the content type to JSON and charset 
        // (charset can be set to something else)
        header("Content-type: application/json; charset=utf-8");
    
        // Set your HTTP response code, 2xx = SUCCESS, 
        // anything else will be error, refer to HTTP documentation
        if ($success) {
            http_response_code(200);
        } else {
            http_response_code(500);
        }
        
        // encode your PHP Object or Array into a JSON string.
        // stdClass or array
        echo json_encode($data);
    
        // making sure nothing is added
        exit();
    }
    
    

    References:

    response_remove

    ob_clean

    Content-type JSON

    HTTP Codes

    http_response_code

    json_encode

提交回复
热议问题