Track Your Websites Rank for Keywords in PHP

When I laid my hands on RankTracker, i was really amazed to see that it can give you how your keywords rank everyday (based on how often you run it).But being a programmer, its one’s intution that makes him to try the same to reproduce it in his skill port.I too did the same thing, I immediately started looking into the html dom specs and stepped in the way of scraping I never did before.

What Actually RankTracker does?

Actually RankTracker Opens up a google search for a keyword you configure and downloads all the first 10 pages in the search.The first 10 pages where there will be approximately 100-130 links will be displayed will be scraped and listed in the count of 1-100.

If your domain appears anywhere between these numbers then you are ranked within 1-100 for these keywords.Else you are told ‘Not in Top 100 sites’.

How To Scrape Google Search?

Google search gives a result screen on searching for a particular term when clicked on Go.( As below).

Ok Now you have searched the data, then what??.

In the screen we can see that the search result screen has links to websites as per google index for the keyword ‘Queen Coffee Maker’.

Say If your site is ‘www.oncoffeemakers.com’, then you must reach the page 5 where your site will be shown in the search results.

So To achieve this we should download all the 10 pages of google search and then in the pages get the links displayed in sequential order and then find where my site is listed. To achieve this we need a small library called ‘simplehtmldom’ which one can download on sourceforge.net.

Coming to the coding part of the RankTracker PHP, you just need to add your keyword and site name to the script below and upload it into a folder on your site and call it when you want to check your sites’ keyword rank in google.

Source Code For Rank Tracker

<?php

/* update your path accordingly */
include_once ‘simplehtmldom/simple_html_dom.php’;

$search_term = “Queen Coffee Maker”;

$search_site = “oncoffeemakers.com“;
$quotes = array();
$count=0;
$keyd=0;
while($count<100)
{
$url = “http://www.google.co.in/search?hl=en&q=”.urlencode($search_term).”&start=$count&sa=N”;

// Create DOM from URL
$html = file_get_html($url);

// Match all ‘A’ tags that have the class attribute equal with ‘l’
foreach($html->find(‘a[class=l]’) as $key => $info)
{
$quotes[$keyd ++]=$info->href;
$count=$count+1;

if(strstr($info->href,$search_site)!=””) break;
}

}

print_r( ‘Your Site Keyword rank is’ + $count);
?>