Saturday, August 11, 2007

Google Trends API in PHP

EDIT: blogger sucks at formatting. If you can't read the code, turn down the font size on your screen really really small, then copy and paste the code into notepad with wordwrap disabled. Or email me! My gmail is zackster.

I wrote this today at DevHouse. You can change the $search URL to whatever you want, just right click the image and figure out its location.



$search = "http://www.google.com/trends/viz?q=paris+hilton&date=2005&geo=all&graph=weekly_img&ctab=0&sa=N";
$source= imagecreatefrompng($search);

$width = imagesx($source);
$blue = array();

for($x=0;$x<$width;$x++) {
for($y=171;$y>0;$y--) {

$pixelrgb = imagecolorat($source,$x,$y);
$cols = imagecolorsforindex($source, $pixelrgb);
$r = $cols['red'];
$g = $cols['green'];
$b = $cols['blue'];

if (($r == 70) && ($g == 132) && ($b == 238)) { // checking that it's the blue line...

array_push($blue, $y);
break;
}
}
}


You can then analyze the $blue array to figure out noteworthy trends. For example, you could do something like this



function sign($diff) {
if($diff > 0) {
return 1;
}
elseif($diff < 0) {
return 2;
}
else {
return 3;
}
}

$threshold = 5;

$i = 0;
$nslc = 0;
foreach($blue as $ele) {

$nslc++;
if($nslc>$threshold) {
$shift = $i - $nslc;
print "WOAH! big shift at $shift
";
}

if (sign($blue[$i+1]-$blue[$i]) != sign($blue[$i]-$blue[$i-1])) { // has the direction changed?
print "direction chnaged at $i
";
$nslc=0;
}

$i++;

}


Now, the code above is imperfect; for example, it doesn't look for brief but extreme deviations. But once you clean the code up a bit, you could easily export data to excel, etc. Good luck.

1 comment:

Unknown said...

Pretty good, thank you Zack.

I found a Google trends php api to get graph, region and related queries data from google trends.