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:
- <alexa ver="0.9" url="php-html.net/" home="0" aid="=">
- <sd title="A" flags="" host="php-html.net">
- <linksin num="20">
- </linksin></sd>
- <sd>
- <popularity url="php-html.net/" text="785463">
- <reach rank="768874">
- <rank delta="-941784">
- </rank></reach></popularity></sd>
- </alexa>
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( '#<popularity url="(.*?)" text="([0-9]+){1,}">#si', $httpResponse, $p );
- $res = ( $p[2] ) ? number_format( intval($p[2]) ):0;
- return str_replace(',', '', $res);
- }
- }
- </popularity>
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
P.S From Editor: I think we can also use DOMDocument object in PHP to retrieve the RANK from the retrieved rank XML from Alexa.Here is the demo code:
$extractor=new AlexaRank();
$doc=new DOMDocument();
$doc->loadXML(file_get_contents($extractor->getRequestUri('pixelstech.net')));
$nodeLisr=$doc->getElementsByTagName('POPULARITY')->item(0);
echo $nodeLisr->getAttribute('TEXT');
Source:http://php-html.net/tutorials/php-class-to-retrieve-alexa-rank/