4

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?


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.

DevinFalgoust
  • 134
  • 1
  • 2
  • 8

2 Answers2

9

Check out file_get_contents

$json = file_get_contents('http://somesite.com/getjson.php');
webbiedave
  • 48,414
  • 8
  • 88
  • 101
  • This does not work. I have to send an HTTP GET to the server, which generates and returns a JSON file. It is not just a file out there which I can access. Because of that, when I try to do this, I get an error that says "failed to open stream". – DevinFalgoust Apr 18 '12 at 20:07
  • 3
    PHP has to be configured appropriately for `file_get_contents()` to retrieve via HTTP and other protocols, but if it is, I second the recommendation to use it. It sounds like it may not be in your case though. Can you provide some info about your PHP configuration? If you have cURL, that's another possibility, as mentioned by the earlier commenter. – JMM Apr 18 '12 at 20:10
  • You have to use cURL or file_get_contents (both of them need to be enabled on php.ini file) to make them work, then your $json variable will be Ok. – Oscar Jara Apr 18 '12 at 20:11
  • 3
    @DevinFalgoust: this _will_ send a HTTP GET request to the server. – Salman A Apr 18 '12 at 20:14
  • 1
    Sorry. The server I was running it on did not have PHP configured to run file_get_contents(). I fixed it, and it worked. – DevinFalgoust Apr 18 '12 at 20:55
2

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:

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

And then echo the JSON string, for example:

//...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:

//...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.

kingmaple
  • 4,200
  • 5
  • 32
  • 44