在 PHP 中从 HTTP Get 接收 JSON 对象

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

Receive JSON object from HTTP Get in PHP

phpjsonhttp

提问by DevinFalgoust

I am trying to implement a php client that sends an HTTP GET to the server which sends back a JSON object with the return information. I know how to decode the JSON once my php script has received it, but how would I go about actually getting it?

我正在尝试实现一个 php 客户端,该客户端将 HTTP GET 发送到服务器,该服务器将带有返回信息的 JSON 对象发回。一旦我的 php 脚本收到它,我知道如何解码 JSON,但我将如何实际获取它?



EDIT: Note - I send the server an HTTP GET, and it generates and sends back a JSON file. It is not a file sitting on the server.

编辑:注意 - 我向服务器发送一个 HTTP GET,它生成并发送回一个 JSON 文件。它不是位于服务器上的文件。

回答by webbiedave

Check out file_get_contents

查看file_get_contents

$json = file_get_contents('http://somesite.com/getjson.php');

回答by kingmaple

Browsers act differently based on what the server responds. It does not matter what type of request you make to the server (be it GET, POST, etc), but to return JSON as a response you have to set the header in the script you make the request to:

浏览器会根据服务器的响应采取不同的行动。您向服务器发出什么类型的请求(GET、POST 等)并不重要,但要返回 JSON 作为响应,您必须在发出请求的脚本中设置标头:

header('Content-Type: application/json;charset=utf-8;');

And then echo the JSON string, for example:

然后回显JSON字符串,例如:

//...populating your result data array here...//
// Print out the JSON formatted data
echo json_encode($myData);

User agent will then get the JSON string. If AJAX made the request then you can simply parse that result into a JavaScript object that you can handle, like this:

然后用户代理将获得 JSON 字符串。如果 AJAX 发出请求,那么您可以简单地将该结果解析为您可以处理的 JavaScript 对象,如下所示:

//...AJAX request here...//
// Parse result to JavaScript object
var myData=JSON.parse(XMLHttp.responseText);

The header itself is not -really- necessary, but is sort-of good practice. JSON.parse() can parse the response regardless.

标头本身并不是 - 真的 - 必要的,但它是一种很好的做法。JSON.parse() 无论如何都可以解析响应。