从PHP脚本返回JSON

Sco*_*col 812 php json header

我想从PHP脚本返回JSON.

我只是回应结果吗?我必须设置Content-Type标题吗?

tim*_*dev 1483

虽然没有它你通常很好,你可以并且应该设置Content-Type标题:

<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
Run Code Online (Sandbox Code Playgroud)

如果我没有使用特定的框架,我通常会允许一些请求参数来修改输出行为.它通常用于快速故障排除,不发送标题,或者有时print_r数据有效负载以引人注目(尽管在大多数情况下,它不是必需的).

  • `标题( '内容类型:应用/ JSON;字符集= UTF-8');` (186认同)
  • @mikepote我实际上并不认为有必要在PHP文件的顶部使用header命令.如果你无意中吐出了东西,并且你的头命令绊倒,你只需要修复你的代码,因为它已经坏了. (14认同)
  • 以防万一:除了输出缓冲之外,你应该只使用header()命令来避免"已发送标题"警告 (9认同)
  • @KrzysztofKalinowski不,PHP文件不需要UTF-8编码.输出必须是UTF-8编码.这些错误的陈述并没有帮助没有经验的用户学习如何避免破坏,但它有助于增加对它们的误解,并且永远不会知道编码在流上扮演的角色以及它们如何工作. (8认同)
  • php文件必须以UTF-8编码,没有BOM :) (5认同)
  • @timdev不要忘记在`echo json_encode($ data);`之后立即调用`die();`的`exit();`,否则脚本中的随机数据(例如,分析)可能会附加到json响应中。 (2认同)

aes*_*ede 114

返回JSON的一整套漂亮而清晰的PHP代码是:

$option = $_GET['option'];

if ( $option == 1 ) {
    $data = [ 'a', 'b', 'c' ];
    // will encode to JSON array: ["a","b","c"]
    // accessed as example in JavaScript like: result[1] (returns "b")
} else {
    $data = [ 'name' => 'God', 'age' => -1 ];
    // will encode to JSON object: {"name":"God","age":-1}  
    // accessed as example in JavaScript like: result.name or result['name'] (returns "God")
}

header('Content-type: application/json');
echo json_encode( $data );
Run Code Online (Sandbox Code Playgroud)


tri*_*cot 39

根据手册上json_encode的方法可以返回非字符串(false):

成功或FALSE失败时返回JSON编码的字符串.

发生这种情况时,echo json_encode($data)将输出空字符串,这是无效的JSON.

json_encode例如,false如果其参数包含非UTF-8字符串,则会失败(并返回).

应该在PHP中捕获此错误情况,例如:

<?php
header("Content-Type: application/json");

// Collect what you need in the $data variable.

$json = json_encode($data);
if ($json === false) {
    // Avoid echo of empty string (which is invalid JSON), and
    // JSONify the error message instead:
    $json = json_encode(array("jsonError", json_last_error_msg()));
    if ($json === false) {
        // This should not happen, but we go all the way now:
        $json = '{"jsonError": "unknown"}';
    }
    // Set HTTP response status code to: 500 - Internal Server Error
    http_response_code(500);
}
echo $json;
?>
Run Code Online (Sandbox Code Playgroud)

然后接收端当然应该知道jsonError属性的存在表明错误条件,它应该相应地处理.

在生产模式下,最好只向客户端发送一般错误状态,并记录更具体的错误消息以供以后调查.

阅读有关在PHP文档中处理JSON错误的更多信息.

  • JSON 没有 `charset` 参数;请参阅 https://tools.ietf.org/html/rfc8259#section-11 末尾的注释:“没有为此注册定义‘字符集’参数。添加一个确实对合规收件人没有影响。” (JSON 必须根据 https://tools.ietf.org/html/rfc8259#section-8.1 以 UTF-8 格式传输,因此将其编码为 UTF-8 有点多余。) (2认同)

the*_*ejh 38

尝试使用json_encode对数据进行编码并设置内容类型header('Content-type: application/json');.


son*_*que 17

这个问题有很多答案,但没有一个涵盖返回干净 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();
}

Run Code Online (Sandbox Code Playgroud)

参考:

response_remove

ob_clean

内容类型 JSON

HTTP 代码

http_response_code

json_encode

  • 感谢 ob_clean 参考。我有一条引导线正在提升我的 fetch response.json() 调用。 (2认同)

Bra*_*ace 15

设置内容类型,header('Content-type: application/json');然后回显数据.


Dr.*_*hno 12

设置访问安全性也很好 - 只需将*替换为您希望能够访问它的域.

<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
    $response = array();
    $response[0] = array(
        'id' => '1',
        'value1'=> 'value1',
        'value2'=> 'value2'
    );

echo json_encode($response); 
?>
Run Code Online (Sandbox Code Playgroud)

以下是更多示例:如何绕过Access-Control-Allow-Origin?


Dan*_*Dan 10

返回带有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();
}
Run Code Online (Sandbox Code Playgroud)


Joy*_*yal 9

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


小智 6

如果你想要 js 对象使用标头内容类型:

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

如果您只想要 json :删除标头内容类型属性,只需编码和回显。

<?php
$data = /** whatever you're serializing **/;
echo json_encode($data);
Run Code Online (Sandbox Code Playgroud)


小智 5

如上所述:

header('Content-Type: application/json');
Run Code Online (Sandbox Code Playgroud)

将工作。但请记住:

  • 即使不使用此标头,Ajax都可以读取json,除非您的json包含一些HTML标记。在这种情况下,您需要将标头设置为application / json。

  • 确保您的文件未使用UTF8-BOM编码。这种格式会在文件顶部添加一个字符,因此您的header()调用将失败。