Here’s a simple and short tutorial on how to retrieve Twitter trends. We will be using PHP and Twitter’s API to retrieve the latest trends. You can publish the trends on your website, blog or any application you are working on. So, let’s get started.
Twitter has made trends available to anyone via API calls. The url of the API is: http://search.twitter.com/trends.json. Trends is also available in XML, but we will use JSON in this example.
To retrieve the string of data, we will use a PHP command called file_get_contents. We will suppress errors by placing an @ sign in front of file_get_contents. We will assign the string to a variable called $contents. So this is what we have so far.
$contents = @file_get_contents("http://search.twitter.com/trends.json"); |
Next, we will check if we have the correct response from the http_header. We will check for the code “200”, meaning we have a valid response. We will use the PHP command called strpos to find the needle in the haystack. The needle in this case is “200.” We will look for it starting at position “0.” The format is going to be like this.
$contents = @file_get_contents("http://search.twitter.com/trends.json"); if (strpos($http_response_header[0], "200")) { echo "ok"; } else { echo "fail" } |
Ok, so we now have a JSON string assigned to the variable named $contents. We just need to decode it using the PHP command called “json_decode” and assign it to the $json array variable. Next, we will run a foreach contruct to echo each trend name.
$contents = @file_get_contents("http://search.twitter.com/trends.json"); if (strpos($http_response_header[0], "200")) { $json = json_decode($contents); foreach ($json->trends as $trend) { echo $trend->name; } } else { } |
So, there you have it. We now have the latest Twitter trends using PHP and Twitter’s API.