我想从PHP脚本返回JSON。

我只是重复结果吗?我必须设置内容类型头吗?


当前回答

<?php
$data = /** whatever you're serializing **/;
header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
?>

其他回答

虽然你通常没有它也没问题,但你可以也应该设置Content-Type头文件:

<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);

如果我没有使用特定的框架,我通常允许一些请求参数修改输出行为。通常对于快速故障排除,不发送报头或有时print_r数据有效负载来观察它(尽管在大多数情况下,这应该是不必要的)是很有用的。

如果你需要从发送自定义信息的php中获取json,你可以添加这个头('Content-Type: application/json');在打印任何其他东西之前,所以然后你可以打印你的自定义echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';

是的,你需要使用echo来显示输出。Mimetype: application / json

你问题的答案在这里,

它说。

JSON文本的MIME媒体类型为 application / json。

所以如果你设置标题为那种类型,并输出你的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