简体   繁体   English

从HTTP接收JSON对象在PHP中获取

[英]Receive JSON object from HTTP Get in PHP

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. 我正在尝试实现一个PHP客户端,该客户端将HTTP GET发送到服务器,该服务器发送回带有返回信息的JSON对象。 I know how to decode the JSON once my php script has received it, but how would I go about actually getting it? 我知道一旦我的PHP脚本收到JSON,就如何解码它,但是我将如何实际获得它呢?


EDIT: Note - I send the server an HTTP GET, and it generates and sends back a JSON file. 编辑:注-我向服务器发送HTTP GET,它生成并发送回JSON文件。 It is not a file sitting on the server. 它不是服务器上的文件。

检出file_get_contents

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

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. 然后,用户代理将获取JSON字符串。 If AJAX made the request then you can simply parse that result into a JavaScript object that you can handle, like this: 如果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()可以解析响应,无论如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM