PHP: Simple method to get data from a JSON Web Service CodeUnit 12 NOV 2012

A lot of web services provide you with some useful JSON formatted data in exchange for a few parameters or just some love, and this is a particularly simple and easy method to grab some of that JSON goodness for use in your own PHP page.

In order to grab the data, we’ll first create a HTTP stream content where we’ll add the all important X-Request-With = XMLHttpRequest header that is used to identify requests as being AJAX requests. At this point you can add any parameters you wish to hit the web service with by adding them as an associative array and wrapping them in a http_build_query() call for the context content.

The next step is to use the classic file_get_contents (this assumes your apache/PHP allows the use of the function to open URLs) to hit the target URL using the newly created context.

This should work, resulting in a JSON object which you can use PHP’s json_decode function to manipulate.

In action:

$opts = array('http' =>
        'method' => 'POST',
        'header' => "Content-type: application/x-www-form-urlencoded\r\nX-Requested-With: XMLHttpRequest\r\n",
        'content' => http_build_query(array())
$context = stream_context_create($opts);
$result = file_get_contents("", false, $context);
$jsondata = json_decode($result, true);


Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.