Google Keywords API PHP

I wrote a PHP script that connects to Google Analytics API
and retreives your top keywords. Google Analytics has a scheduler
that can send you emails of your keywords, but this script can be
used to return various formats and then be sent to another program
or logged for further processing. The first couple lines have to do
with the start-date and end-date of the statistics to return.
Currently it’s set-up to run on a cron on the first of every month
and send me a report of the last months keywords. This can easily
be changed by modifying the startDate and endDate variables. The
Table ID which is the ID of your site in analytics, is set to
retrieve it’s value as the first param given on the command line.
So if your table id was 123456, you would call the script as “php
googleAnalyticsFeed ga:123456”.

define("GoogleUserEmail", "YOUR_EMAIL_HERE");
define("GoogleUserPass", "YOUR_PASSWORD_HERE");
""); #(First/Last day of
previous month) $lastDayOfMonth = date('Y-m-d', strtotime("-1
second ".date('m').'/01/'.date('Y'))); $firstDayOfMonth =
date('Y-m-01', strtotime("-1 second ".date('m').'/01/'.date('Y')));
$table = $argv[1]; # Table ID for Site $startDate =
$firstDayOfMonth; #Start Date to Search $endDate = $lastDayOfMonth;
# End Date to Search $max = 100; # Max-results to display #Auth
String $auth = googleAuth(GoogleUserEmail, GoogleUserPass); #Get
XML Keyword Data $xml = getKeywords($auth, $table, $startDate,
$endDate, $max); #Loop Through Results and Display (Count -
Keyword) $dom = new DomDocument(); $dom->loadXML($xml); $entries
= $dom->getElementsByTagName('entry'); foreach ($entries as
$entry) { $keyword =
'dimension')->item(0)->getAttribute('value'); $total =
'metric')->item(0)->getAttribute('value'); printf("%5d -
%s\n", $total, $keyword); } #Get Google Auth function
googleAuth($email, $pass) { $ch = curl_init(GoogleClientLoginURL);
$postParams = array( "Email" => $email, "Passwd" => $pass,
"accountType" => "GOOGLE", "source" => "curl-dataFeed-v2",
"service" => "analytics"); curl_setopt($ch, CURLOPT_POSTFIELDS,
http_build_query($postParams)); curl_setopt($ch, CURLOPT_HEADER,
0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch,
CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch);
preg_match('/Auth=.*/', $data, $auth); return $auth[0]; } #Get
Google Keywords function getKeywords($auth, $table, $startDate,
$endDate, $max) { $getParams = array( "ids" => $table,
"start-date" => $startDate, "end-date" => $endDate,
"dimensions" => "ga:keyword", "metrics" => "ga:visits",
"sort" => "-ga:visits", "max-results" => $max, "prettyprint"
=> "false"); $ch =
$header[0] = "Authorization: GoogleLogin $auth"; $header[1] =
"GData-Version: 2"; curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST,
0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data =
curl_exec($ch); return $data; }