22 May, 2010

Get trends in twitter using curl

Following code is used to get current trends in twitter using curl. Its quite simple. Getting current trends from twitter
requires no authentication, so we jost use curl with the trends url provided by twitter api. The response is
json format, and we process the response to display all the trends as links to the trends. It returns top 10 trends
of twitter.

//get the trends url with result as json format
$url = "http://search.twitter.com/trends/current.json";
//initialize the curl with trends url
$ch = curl_init($url);
//set option to return result as string to process it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute curl
$resp = curl_exec($ch);
//use json_decode of php to decode the json format response
$trends = json_decode($resp, true);
//get the date set as key in trends
$key = key($trends["trends"]);
//set the array
$trendsArr = $trends["trends"][$key];
foreach($trendsArr as $key => $value) {
//$value is an array with keys name and query, query is used in a href link and name displayed as trend name as follows
echo "".$value["name"]."

No comments: