PHP Code Get Alexa Rank and Site Linking
In this post, I will explain how to use PHP code to get Alexa rank and site linking of your blog or website using a simple PHP script
How to Find Alexa Rank?
The PHP code to get Alexa rank and sites linking in is pretty simple and straightforward:
The URL to get the Alexa rank and some other useful fields in XML format is:
1 |
http://data.alexa.com/data?cli=10&dat=snbamz&url=www.your-domain.com |
Note that it has several important fields like popularity, DMOZ listings, the countries in which the site is most popular etc.
To parse this XML file either you can use regular expression match or use initialize curl with given url. here i am doing this with curl_init()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php function initialize_curl($url) { if(function_exists('curl_init')) { $ch = curl_init($url); // initialize curl with given url curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // add useragent curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable if((ini_get('open_basedir') == '') && (ini_get('safe_mode') == 'Off')) { curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // max. seconds to execute curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error return @curl_exec($ch); } else { return @file_get_contents($url); } } ?> |
How to get the Alexa rank and Site Linking from PHP?
Here I’ going to show an easy way to get alaxa rank information of your website or other website by using php code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php function getAlexaRank($domain) { $request = "http://data.alexa.com/data?cli=10&dat=s&url=" . $domain; $data = getPageData($request); preg_match("/<POPULARITY URL="(.*?)" TEXT="([\d]+)"/si", $data, $p); $value = ($p[2]) ? number_format($p[2]) : "n/a"; $string = "<a href=\"http://www.alexa.com/siteinfo/" . $domain . "\">" . $value . "</a>"; return $string; } function getAlexaLinks($domain) { $request = "http://data.alexa.com/data?cli=10&dat=s&url=" . $domain; $data = getPageData($request); preg_match('//si', $data, $l); $value = ($l[1]) ? number_format($l[1]) : "n/a"; $string = "<a href=\"http://www.alexa.com/site/linksin/" . $domain . "\">" . $value . "</a>"; return $string; } > |
The Usage
Provide one paramenters: your domain.
1 2 3 4 |
<?php echo 'Rank: '.getAlexaLinks('www.your-domain.com'); // returns Rank: 118 echo 'Links In: '.getAlexaLinks('www.your-domain.com'); // returns Links In: 34,414 ?> |
This Demo Alexa Rank checker
Note: You can add a widget alexa rank checker to your webpage Free Alexa Rank Checker Widget