Alexa is a service acquired by Amazon which offers a web traffic report for websites. They retrieve the data from toolbar that can be installed in different browsers, centralize the data and display reports to anyone. The most important indicator is the Alexa Rank. It represents the rank of a webpage in a list of all the websites. It’s not the 100% accurate but it gives a good indication.

Alexa 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.

Did you enjoy this tutorial? Be sure to subscribe to the our RSS feed not to miss our new tutorials!
... or make it popular on