我想从PHP脚本返回JSON。
我只是重复结果吗?我必须设置内容类型头吗?
我想从PHP脚本返回JSON。
我只是重复结果吗?我必须设置内容类型头吗?
当前回答
这个问题有很多答案,但没有一个涵盖了返回干净JSON的整个过程,以及防止JSON响应变形所需的一切。
/*
* 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();
}
引用:
response_remove
ob_clean
JSON内容类型
HTTP规范
http_response_code
json_encode
其他回答
如果你想要js对象,使用头content-type:
<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
如果你只想要json: remove header content-type属性,只需要encode和echo。
<?php
$data = /** whatever you're serializing **/;
echo json_encode($data);
尝试json_encode对数据进行编码,并设置带有header的content-type (' content-type: application/json');
一个返回带有HTTP状态代码的JSON响应的简单函数。
function json_response($data=null, $httpStatus=200)
{
header_remove();
header("Content-Type: application/json");
http_response_code($httpStatus);
echo json_encode($data);
exit();
}
虽然你通常没有它也没问题,但你可以也应该设置Content-Type头文件:
<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
如果我没有使用特定的框架,我通常允许一些请求参数修改输出行为。通常对于快速故障排除,不发送报头或有时print_r数据有效负载来观察它(尽管在大多数情况下,这应该是不必要的)是很有用的。
这个问题有很多答案,但没有一个涵盖了返回干净JSON的整个过程,以及防止JSON响应变形所需的一切。
/*
* 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();
}
引用:
response_remove
ob_clean
JSON内容类型
HTTP规范
http_response_code
json_encode