[On Special Request] How to Query the Twitter trends API to get latest trends in real time

Nishant Arora 15/Oct/2012
Facebook
Twitter
LinkedIn
Reddit

hi,

I was just contacted by a reader of my blog Mikel Iturrioz, an internet passionate (as he claims himself to be) and had reached my blog through a client project available http://clients.nishantarora.in/projects/twitter_trends/. Now since it is a client project and I have been paid to do this, I doubt I can share this code freely, but the idea is something available for free and let me try to explain what I did here.

Step 1: Understanding the twitter trends API:

you can get the latest country trends by getting the URL http://api.twitter.com/1/trends/.json , the output will be a a json string containing latest trends of the respective WOEID. Now you need to understand what the WOEID is. WOEIDs are IDs issued to all the place entities around the world, Countries, cities, states, etc. To search more about the WOEIDs http://sigizmund.info/woeidinfo/ is a good place to start.

Here is a List of some common WOEIDs in PHP array format:

<?php

$woeid["Worldwide"]    = "1";
$woeid["US"]      = "23424977";
$woeid["Canada"]    = "23424775";
$woeid["France"]    = "23424819";
$woeid["UK"]      = "23424975";
$woeid["Mexico"]    = "23424900";
$woeid["Japan"]      = "23424856";
$woeid["Brazil"]    = "23424768";
$woeid["Netherlands"]  = "23424909";
$woeid["Indonesia"]    = "23424846";
$woeid["India"]      = "23424848";
$woeid["Venezuela"]    = "23424982";

?>

Step 2:  Creating a simple function to get trends from what we have learnt above

Does the following function need any explanation?...

function get_trends($woeid){
  return json_decode(@file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json", true), false);
}

Step 3: Outputting the data.

I think this is the most easiest part...

$data = get_trends($_GET['id']);
  if(!empty($data)){
    $country = $data[0]->locations[0]->name;
    $as_of = date("g:i a\, F j\<\s\u\p\>S\<\/\s\u\p\> Y", strtotime($data[0]->as_of));
    $created = date("g:i a\, F j\<\s\u\p\>S\<\/\s\u\p\> Y", strtotime($data[0]->created_at));
    $trends = $data[0]->trends;
    echo "Country: ".$country."<br>As Of: ".$as_of."<br>Created At: ".$created."<ul>";
    foreach($trends as $trend){
      echo '<li><a href="'.$trend->url.'" target="_blank" rel="noopener noreferrer">'.$trend->name.'</a></li>';
    }
  }else{
    echo 'Twitter Seems To Be Not Responding!...';
  }

Checkout this in action here http://clients.nishantarora.in/projects/twitter_trends/?id=23424977

Step 4: Adding AJAX Magic (OPTIONAL)

this is totally upto you how you wanna interface that with the data on your website. you can add some fancy AJAX or can just reload on a new request, Sky's the Limit

Hope I explained every bit of it, clearly and as easy as possible. Thanks to my readers, this really encourages me!

Cheers!... Keep Hacking!...