Click here to Skip to main content
15,908,661 members
Articles / Programming Languages / PHP
Tip/Trick

Alexa ranking using php script

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
15 Nov 2010CPOL 19.7K   4   1
if you want to check the your website ranking as per alexa so you can use the following code in your php projects.
http://data.alexa.com/data?cli=10&dat=s&url=how2dev.com
“http://data.alexa.com/data” this file will return the xml format output. Using the XML output or reading xml file we can easily fetch the our or any website ranking.
Use the following function for getting the alexa website ranking.


function AlexaRank( $url )
{
preg_match( '#<POPULARITY URL="(.*?)" TEXT="([0-9]+){1,}"/>#si', file_get_contents('http://data.alexa.com/data?cli=10&dat=s&url=' . $url), $p );
return ( $p[2] ) ? number_format( intval($p[2]) ):0;
}
echo "wordpressapi.com Rank as per alexa.com: ";
echo AlexaRank('how2dev.com');
?>


if you want to check the multiple website ranking in one shot than use the following PHP code.

$domains = array( 'google.com', 'ask.com', 'yahoo.com', 'bing.com' );

foreach ( $domains as $domain )
echo $domain, ' - ', AlexaRank( $domain ), '<br />', PHP_EOL;

?>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Estonia Estonia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralPreg_match return Pin
PhilLeTaxi22-Nov-10 5:11
PhilLeTaxi22-Nov-10 5:11 
Thanx for the tip. Thumbs Up | :thumbsup:

I suggest to test the return of preg_match() as for some URL the information related
to popularity is missing, and/or the information related to the URL is very different
from one URL to another.
(for example, the script generates an error with alexa.com).

function AlexaRank( $url )
{
    $report = preg_match( '#<POPULARITY URL="(.*?)" TEXT="([0-9]+){1,}"/>#si', file_get_contents('http://data.alexa.com/data?cli=10&dat=s&url=' . $url), $p );
    if( ($report == 0) || ($report === False) )
        return "Popularity for this url not found";
    else
        return ( $p[2] ) ? number_format( intval($p[2]) ) : 0;
}

$l_url = 'alexa.com';
echo "Rank of <strong>".$l_url."</strong> as per alexa.com : ";
echo AlexaRank($l_url);


The example above returns :
"Rank of alexa.com as per alexa.com : Popularity for this url not found"

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.