何时在 PHP 中使用 header('Content-Type: application/json')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44378222/
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-26 02:58:50  来源:igfitidea点击:

When to use header('Content-Type: application/json') in PHP

phphttpcurlhttp-headers

提问by naspy971

I've been trying to figure out what's really the usage of header('Content-Type: application/json')in php scripts and I've found different questions and answers on stackoverflow about this subject but I still don't completely get it...

我一直在试图弄清楚header('Content-Type: application/json')php 脚本的真正用途是什么,我在 stackoverflow 上找到了关于这个主题的不同问题和答案,但我仍然没有完全理解它......

So here's the question : I've seen in some php projects this line of code, and I'm trying to understand

所以这里的问题是:我在一些 php 项目中看到过这行代码,我试图理解

  • if this is used when another web page is calling this actual script (with ajax for example) so that the calling page can get a json from the php page
  • 如果在另一个网页调用此实际脚本(例如使用 ajax)时使用它,以便调用页面可以从 php 页面获取 json

OR

或者

  • if this script means that the php page is going to deal with json sent from another web page. Or maybe something else ???
  • 如果此脚本意味着 php 页面将处理从另一个网页发送的 json。或者别的什么???

Another thing that could help me if answered, lately I've been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?

如果得到回答,另一件事可以帮助我,最近我一直在使用 cURL 从资源(外部 url)中检索 json,我不得不将这个标头 (Content-type:application/json) 放在请求中。我是将这个标头发送到 expernal 资源还是我的标头,以便我可以处理返回的 json ?

thanks

谢谢

回答by naspy971

Ok for those who are interested, I finally figured out that header('Content-Type: application/json')is used when another page is calling the php script, so that the other page can automatically parse the result as json.

好吧,有兴趣的朋友,我终于想通了,header('Content-Type: application/json')在另一个页面调用php脚本时使用的,这样另一个页面就可以自动将结果解析为 json

For instance i have in my test.php :

例如我在我的 test.php 中有:

header('Content-type: application/json; charset=utf-8');
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}

and in my main.js

在我的 main.js 中

function test() {
    $.ajax({
        url: 'test.php',
        type: 'GET',
        //dataType: 'html',
        success: function (response) {
            alert(response);
        }
    });
};

When I dont have dataType set to "json" or when I don't have the header in my test.php, the alert gives {"a":1,"b":2,"c":3,"d":4,"e":5}which is a string (tried with typeof(response), and when I have this header, or dataType:"json", I get [object Object]from the alert. So this header function is there to indicate to the calling pages which type of data it gives back, so that you can know how to deal with it. In my script, if I didn't have header('Content-Type: application/json'), I would have to parse the response in the javascript like this : JSON.parse(response)in order to make it a json, but with that header, I already have a json object, and I can parse it to html with jSON.stringify(response).

当我没有将 dataType 设置为“json”或者我的 test.php 中没有标题时,警报会给出{"a":1,"b":2,"c":3,"d":4,"e":5}一个字符串(尝试使用 typeof(response),当我有这个标题或 dataType 时: “json”,我[object Object]从警报中得到。所以这个头函数是为了向调用页面指示它返回哪种类型的数据,这样你就可以知道如何处理它。在我的脚本中,如果我没有有header('Content-Type: application/json'),我必须像这样解析javascript中的响应:JSON.parse(response)为了使其成为json,但是使用该标头,我已经有了一个json对象,我可以将其解析为html jSON.stringify(response)

回答by SLaks

You should always set the Content-Typefor any HTTP response to describe what you're serving in that response.

您应该始终Content-Type为任何 HTTP 响应设置 ,以描述您在该响应中提供的服务。

Whether it's JSON or something else, and whether it's for an AJAX request or any other kind of request.

无论是 JSON 还是其他东西,无论是针对 AJAX 请求还是任何其他类型的请求。



You should also set the Content-Typefor any requestto describe your POST payload.

您还应该Content-Type为任何请求设置来描述您的 POST 负载。

回答by JoshA

In PHP, if you don't specify the Content-Typeheader in the script, it will default to whatever you've configured default-mimetypeto be in your php.inifile which is usually text/html.

在 PHP 中,如果您没有Content-Type在脚本中指定标头,它将默认为您在文件中配置的任何default-mimetypephp.ini通常是text/html.

Calling header('Content-Type: application/json')will override that default setting so that the script will respond with that Content-Typewhen requested.

调用header('Content-Type: application/json')将覆盖该默认设置,以便脚本Content-Type在请求时响应该设置。

Also, when calling curlwith a Content-type:application/jsonheader, you're specifying the content type for your request body and not for the expected reponse.

此外,在curl使用Content-type:application/json标头进行调用时,您正在为请求正文指定内容类型,而不是为预期的响应指定内容类型。

回答by Haidar Zeineddine

W3 Description For the Content-Type

W3 内容类型的描述

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

Content-Type 字段的目的是充分描述包含在正文中的数据,以便接收用户代理可以选择合适的代理或机制将数据呈现给用户,或者以适当的方式处理数据。

Shortly speaking, just to inform the receiver what kind of data he received and consume it accordingly.

简而言之,只是为了通知接收者他收到了什么样的数据并相应地消费它。