Hey Folks,

There are times when you need to fetch data from certain URL. This URL can give you RSS feeds or it can be a JSON data. But while writing a script you may often face challenge to fetch the contents from the URL. Some programmers use file_get_contents() function of PHP to get the data from the URL, but by default the http is not supported in the argument of this function. So to get the contents from a URL you have to make a curl request. The procedure to do the same is as follows.

<?php
$url='http://twitter.com/statuses/user_timeline/16387631.json'; //rss link for the twitter timeline
print_r(get_data($url)); //dumps the content, you can manipulate as you wish to
 
/* gets the data from a URL */
 
function get_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);
curl_close($ch);
return $data;
}
?>

This is really important function and can be used in multiple ways. In the above example I am fetching my tweets in the form of JSON. You do not need any authentication to do that and hence you can get the output. But some URLs which need to be authenticated may not return anything but an error. So  you have to take care of that. This function is pretty basic example of CURL request.

You can enhance this function and have fun.

Stay Digified !!
Sachin Khosla

Share this post: