从 PHP 脚本返回 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4064444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:51:11  来源:igfitidea点击:

Returning JSON from a PHP Script

phpjsonheader

提问by Scott Nicol

I want to return JSON from a PHP script.

我想从 PHP 脚本返回 JSON。

Do I just echo the result? Do I have to set the Content-Typeheader?

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

回答by timdev

While you're usually fine without it, you can and should set the Content-Type header:

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

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

If I'm not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn't be necessary).

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

回答by aesede

A complete piece of nice and clear PHP code returning JSON is:

一段完整的、清晰的返回 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 );

回答by trincot

According to the manual on json_encodethe method can return a non-string (false):

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

Returns a JSON encoded string on success or FALSEon failure.

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

When this happens echo json_encode($data)will output the empty string, which is invalid JSON.

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

json_encodewill for instance fail (and return false) if its argument contains a non UTF-8 string.

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

This error condition should be captured in PHP, for example like this:

这个错误条件应该在 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(["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;
?>

Then the receiving end should of course be aware that the presence of the jsonErrorproperty indicates an error condition, which it should treat accordingly.

那么接收端当然应该知道jsonError属性的存在表明一个错误条件,它应该相应地处理。

In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation.

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

Read more about dealing with JSON errors in PHP's Documentation.

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

回答by thejh

Try json_encodeto encode the data and set the content-type with header('Content-type: application/json');.

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

回答by Brad Mace

Set the content type with header('Content-type: application/json');and then echo your data.

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

回答by Dr. Aaron Dishno

It is also good to set the access security - just replace * with the domain you want to be able to reach it.

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

<?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); 
?>

Here is more samples on that: how to bypass Access-Control-Allow-Origin?

这里有更多示例:如何绕过 Access-Control-Allow-Origin?

回答by Joyal

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

回答by Tom Ah

As said above:

如上所述:

header('Content-Type: application/json');

will make the job. but keep in mind that :

将完成这项工作。但请记住:

  • Ajax will have no problem to read json even if this header is not used, except if your json contains some HTML tags. In this case you need to set the header as application/json.

  • Make sure your file is not encoded in UTF8-BOM. This format add a character in the top of the file, so your header() call will fail.

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

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

回答by Dan

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

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

回答by Codemwnci

The answer to your question is here,

你的问题的答案在这里

It says.

它说。

The MIME media type for JSON text is application/json.

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

so if you set the header to that type, and output your JSON string, it should work.

因此,如果您将标头设置为该类型,并输出您的 JSON 字符串,它应该可以工作。