我想从PHP脚本返回JSON。

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


当前回答

如果你想要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);

其他回答

一个返回带有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();
}

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

用header(' content -type: application/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

这是一个简单的PHP脚本,返回男性女性和用户id作为json值将是任何随机值,因为你调用脚本json. PHP。

希望能有所帮助,谢谢

<?php
header("Content-type: application/json");
$myObj=new \stdClass();
$myObj->user_id = rand(0, 10);
$myObj->male = rand(0, 5);
$myObj->female = rand(0, 5);
$myJSON = json_encode($myObj);
echo $myJSON;
?>