Google Keywords API PHP

Posted by Tully on Tue 10 May 2011

Today 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 analytics ad-hoc. It can also be used to send the data to other programs or log it for further processing.

The first couple lines have to do with the start-date and end-date of the statistics to return. Currently I have the script set-up to run on a cron on the first of every month. This way it can provide me with me a report of the last months keywords. This can easily
be changed by modifying the startDate and endDate variables.

The Table ID is the ID of your site in analytics, it'sset to
retrieve it's value as the first parameter given on the command line.
So if your table id was 123456, you would call the script as php googleAnalyticsFeed ga:123456.

define("GoogleNameSpace", "");
define("GoogleClientLoginURL", "");
define("GoogleUserEmail", "YOUR_EMAIL_HERE");
define("GoogleUserPass", "YOUR_PASSWORD_HERE");
define("GoogleFeedURL", "");

#(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();
$entries = $dom->getElementsByTagName('entry');

foreach ($entries as $entry) {
    $keyword = $entry->getElementsByTagNameNS(GoogleNameSpace, 'dimension')->item(0)->getAttribute('value');
    $total = $entry->getElementsByTagNameNS(GoogleNameSpace, '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 = curl_init(GoogleFeedURL.'?'.http_build_query($getParams));
    $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;