Returning JSON from a PHP Script

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

    A simple function to return a JSON response with the HTTP status code.

    function json_response($data=null, $httpStatus=200)
    {
        header_remove();
    
        header("Content-Type: application/json");
    
        http_response_code($httpStatus);
    
        echo json_encode($data);
    
        exit();
    }
    

提交回复
热议问题