PHP Code to Grab Alexa Traffic Ranking

Written by Omar Kattan. Filed under Code. Bookmark the Permalink. Post a Comment. Leave a Trackback URL.

Here is a php code that lets you retrieve a website’s alexa ranking, useful in web applications that measure importance of webpages (such as bespoke link popularity tools).

For this code snippet to work CURL library for php needs to be enabled on your server.

Code:

 <?php
 function alexaRank($domain)
 {
$ch = curl_init(‘http://alexa.com/data/details/traffic_details?url=’.$domain);
    curl_setopt($ch, CURLOPT_TIMEOUT, 50);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, ”Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1″);
    $curl_ret = curl_exec($ch);
    curl_close($ch);
    
    $curl_ret = explode(‘Visit http://aws.amazon.com/awis for more information about the Alexa Web Information Service.–>’, $curl_ret);
    $curl_ret = array_shift(explode(‘<br’,$curl_ret[1]));
    $ret = ”;
    $ignore = false;
    for($i=0;$i<strlen($curl_ret);$i++)
    {
  if ( is_numeric($curl_ret{$i}) && !$ignore )
   $ret .= $curl_ret{$i};
  else if ( $curl_ret{$i} == ’<’ )
   $ignore = true;
  else if ( $curl_ret{$i} == ’>’ )
   $ignore = false;
}
    return (int)$ret;
 }

To display the Alexa ranking, use the following code :

echo alexaRank(‘site.com’);

One Comment

  1. martinlock
    Posted December 9, 2008 at 12:09 pm | Permalink

    It is obvious that with every passing day the credibility of Alexa is only increasing and getting stronger. The mammoth number of users that is always increasing and the tough competition to the top is testimonial to this fact.

Post a Comment

You must be logged in to post a comment.