Build an Alexa rank checker

In this tutorial we will be building an Alexa rank checker, a web tool, like the one hosted here, which allows users to check the Alexa rank of any website inputted.We will be using the simplexml_load_file function, this is only available in PHP5.

The HTML

First up create a file called alexachecker.html and put in the below HTML. This will create a simple form with a textbox to input a URL and a submit button to process the form. The method is set to GET so the form data is sent via the URL.








This form will look something like this:

The PHP

Next we create a file called alexachecker.php, this will find the rank for the given URL.

Obtaining the requested URL

The first part of the PHP code is to obtain the URL the user has requested the rank for. This is done by using the $_GET array. The PHP below obtains the URL and stores it in a variable called $url

= $_GET['url'];
?>

Getting the rank

In order to get the rank for the URL we use this XML file provided by Alexa: http://data.alexa.com/data?cli=10&dat=s&url=URL goes here, for example: http://data.alexa.com/data?cli=10&dat=s&url=http://www.spyka.net

We insert the URL provided by the user into the Alexa URL using {$url} as shown by the code below:

= $_GET['url'];

$data_url = “http://data.alexa.com/data?cli=10&dat=s&url={$url}”;
?> Next step is to get this XML data into the PHP code for use. simplexml_load_file will convert the XML document into an object:

= $_GET['url'];

$data_url = “http://data.alexa.com/data?cli=10&dat=s&url={$url}”;

$data = simplexml_load_file($data_url) or die(“Could not load data”);
?> The or statement will stop the script and output an error if the function fails.

Lastly we get the Alexa rank for the given domain by referencing the appropriate element of the $data object, this is then stored in a variable called $rank.

= $_GET['url'];

$data_url = “http://data.alexa.com/data?cli=10&dat=s&url={$url}”;

$data = simplexml_load_file($data_url) or die(“Could not load data”);

$rank = $data->SD->POPULARITY['TEXT'];
?>

Outputting the rank

Last part of the PHP code is to output the rank. We use a simple if…else statement to check the rank is above 0 before outputting. If it isn’t an error will be shown - this would be caused by an incorrect URL or a URL which doesn’t currently have a rank (a new website)

= $_GET['url'];

$data_url = “http://data.alexa.com/data?cli=10&dat=s&url={$url}”;

$data = simplexml_load_file($data_url) or die(“Could not load data”);

$rank = $data->SD->POPULARITY['TEXT'];

if($rank > 0)
{
echo
“The Alexa rank for this website is {$rank}”;
}
else
{
echo
“Could not obtain rank”;
}
?> And that’s it - your Alexa rank checker is complete!

0 comments:

Post a Comment