Whilst at work today, I discussed with someone whether it would be possible to gain Twitter’s trending topics. Instantly, I knew yes. But then the question arose about whether you could depending on the location of the user.
For the past two hours, I have been looking into the Twitter API and gaining location information from an IP address. Luckily, I came up with a suitable solution.
A quick look at the Twitter trends API and I can see that it would need to be broken down into two sections. Finding out the WOE ID (Where On Earth) of the country and then sending that WOE to another API that will deliver the trends. To work out the WOE ID, there are several properties that can be compared such as Name and Country. Name being the name of the country or a name of a location such as London or Glasgow or Country which is… the country.
Back to the IP and if you’re wondering why I chose to use the user’s IP address instead of recent functionality from browsers geolocation, it would be because not all browsers have it thus saving a lot of time to check whether they do and if not falling back onto the IP.
There are quite a few IP to location website’s out there which initially were free to use but due to popular demand, they have offered a free for so many but pay after a certain amount scheme. I’m my mind, I knew that what the person I was speaking wanted it for, wanted it for a VERY large purpose so it would almost ultimately end up with them needing to spend money. However, I found a free site that still offers the IP to location.
http://www.hostip.info/ offers this delightful service. Simple use of their API, returns an XML with country name, latitude and longitude.
Below is my code with comments just to help you understand my thought process. Most probably an easier way, but this is a solution.
[code]
<?php
//Declare the basic URL
$URL = "http://api.hostip.info/?ip=".$_SERVER['REMOTE_ADDR'];
//Page returns XML, so load
$tmpXML = new DOMDocument();
$tmpXML->load($URL);
//Get country value
$userCountry = $tmpXML->getElementsByTagName('countryName')->item(0)->nodeValue;
//We now need to get the country's woeid from this URL:
//http://api.twitter.com/1/trends/available.json
$twitterWoeIDs = json_decode(file_get_contents("http://api.twitter.com/1/trends/available.json"));
//Search the JSON for our country
for($i=0;$i<count($twitterWoeIDs);$i++) {
if(strtolower($userCountry)==strtolower($twitterWoeIDs[$i]->name)) {
$found = true;
break;
}
}
//UK is 21125
if($found!=true) {
//If not found, set a default of United Kingdom
$userWOEID = "23424975";
} else {
$userWOEID = $twitterWoeIDs[$i]->woeid;
}
//Then put the woeid in this URL
//http://api.twitter.com/1/trends/[WOEID].json
$URL2 = "http://api.twitter.com/1/trends/".$userWOEID.".json";
$twitterTrendJSON = json_decode(file_get_contents($URL2));
//Loop through the trends
for($i=0;$i<count($twitterTrendJSON[0]->trends);$i++) {
echo $twitterTrendJSON[0]->trends[$i]->name."<BR>";
}
?>
[/code]