kklimuk

quip i: retrieve webapp data with php

In PHP on June 24, 2011 at 6:41 pm

This is a small PHP tutorial to solve the problem of retrieving data from a web application.

Most web applications (think FB or Twitter) often use JSON (javascript object notation) in order to send data to the user. PHP happens to contain a great set of tools for decoding the JSON data that you receive from these sites: json_decode. However, retrieving the data from a remote url is the bigger problem in modern versions of PHP (think >4). The old fopen() approach no longer works on most servers due to security reasons, leaving cURL as the best option.

Following that logic, I’ve written a function that will retrieve data from a remote url using cURL and decodes it. *

function get_url_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
if ($data) {
return json_decode($data);
}
else {
return false;
}
}

Now, let’ retrieve the data using this function. In this case, I will be retrieving tweets for a specific screen name:

$screen_name = name /*some screen name here*/;

$url = “http://api.twitter.com/1/users/show.json?screen_name=$screen_name&callback=?”

// get the contents of the url

$data = get_url_data($url);

if($data) { // check if data was retrieved

// get the user image url
$picture = $data->profile_image_url;
// do something with the data here 

}

$data will return an object of class stdClass, which is the default class that PHP resorts to.

That’s it! Using this code, you will be able to extract data from most sites that use JSON.

*NOTE: clicking on individual links will take you to the PHP manual pages for the function.

Leave a comment