Php Class to Retrieve Alexa Rank
api, parsing February 28th, 2010Alexa does not offer any free API to obtain Alexa Rank. However there is a simple method to obtain it in the same way the Alexa Toolbar does. All you have to do is to invoke the following url(replacing php-html.net with your domain): http://data.alexa.com/data?cli=10&dat=s&url=php-html.net
The response should look like this one:
All we have to do is to take the response and extract the Alexa Rank from it. There are various options, we are just going to use a simple regular expression:
class AlexaRank
{
public function getRequestUri($domain)
{
return 'http://data.alexa.com/data?cli=10&dat=s&url=' . $domain;
}
public function parse( $httpResponse )
{
preg_match( '# #si', $httpResponse, $p );
$res = ( $p[2] ) ? number_format( intval($p[2]) ):0;
return str_replace(',', '', $res);
}
}
Then we can simply get the alexa rank:
echo $extractor->parse(file_get_contents($extractor->getRequestUri('php-html.net')));
The extractor class contains the 2 functions one to build the url to be invoked for a domain and the second one to parse the response. This solution was chosen offer the option to use an external function that retrieve the response content. This is because for some hosting servers the file_get_contents does not work, for other curl does not work…
Remember the “use it but not abuse it” concept. Alexa didn’t expose this through a public api for some reason. If you use this function zillions times a day you will probably be detected and have the ip banned.




March 1st, 2010 at 2:49 pm
Really? You’ve got an XML response and you’re going to parse it with … regular expressions. I believe you should be using the xPath to get the value.
March 28th, 2010 at 2:36 am
cool idea, unfortunately the alexa link doesnt work anymore.
I agree with mathew that there are far better/faster ways of parsing this data
one would be simply to load the response string into a xml php object
May 3rd, 2010 at 3:00 am
Thanks for your code. I have tried but I did not get result. Could you please send / post full source code.
June 20th, 2010 at 6:53 pm
Try this:
Change :
preg_match( ‘##si’, $httpResponse, $p );
To :
preg_match( ‘##si’, $httpResponse, $p );
And then:
$extractor = new AlexaRank();
echo $extractor->parse(file_get_contents($extractor->getRequestUri(’php-html.net’)));