This page looks best with JavaScript enabled

How to get your Alexa Rank count and Pagevies using php

 ·  ☕ 2 min read  ·  👽 john hashim

have you ever wondered how site value script or webmaster tools get your Alexa ranking number? , Well it nothing fancy or complicated justing using the existing Url parameter from amazon Alexa ranking to access your domain rank using PHP .. which involves about XML and so many complicated stuff but in this post, I’m not going to go into ‘ How to ‘ space.

so first you create your function to define your two variables which is $domain and $format well in this post we won’t go into formats so it will be set to false since I’m not diving into deep Analytics. Then the rest will be history but this is the snippet.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php
function alexa($domain,$format = FALSE){
$url = 'https://data.alexa.com/data?cli=10&dat=snbamz&url=';
$url .= $domain;

$xml = simplexml_load_file($url);

if (isset($xml->SD[1]->POPULARITY))
 $data = (int) $xml->SD[1]->POPULARITY->attributes()->TEXT;
 if($format) return number_format($data);
 return $data;

}
//post this anywere in your file

echo alexa('https://www.johnhashim.com',TRUE);

?>

this is the code I used o my home page to get my Alexa ranking for sure it has no use to my site but I want to see how my name is ranking on the web which is bit childish.. 😉

The second snippet I used was the pageviews count basically this will count every time you refresh the page and I’m not sure if it’s based per browser but I’m here to find out. but my Goal was to Insight plugins functions or variable and be able to display my monthly page views which didn’t work since I can find that out so instead, I used this snippet.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php
function setAndViewPostViews($postID) {
    $count_key = 'views';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
    return $count; /* so you can show it */
}

// then you can call this in your files.

echo setAndViewPostViews(get_the_ID());
?>

lastly, it was the post count which is really the simplest thing to do from any script you might be using … In my case since this is WordPress, I used WP functions according to the codex reference

1
2
3
4
5
<?php
$count_posts = wp_count_posts();
$published_posts = $count_posts->publish;
echo $published_posts;
?>
Share on

john hashim
WRITTEN BY
john hashim
Web Developer