7/12/2011

Get data from a URL using cURL PHP

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

SHARE THIS

Author:

Tôi là PHƯỚC kỹ sư công nghệ thông tin. chuyên thiết kế web và làm dịch vụ MMO.

0 comments: