April 22nd, 2009, by alex

Using the Google Analytics API - getting total number of page views

At long last, Google released the Google Analytics API.  The timing couldn’t be better, since I was just trying to get to some information through screen scraping… which is never fun.

The API is pretty easy to use, and other than a typo which slowed me down way too much, it didn’t take long to write a simple PHP script to get the total number of page views across all my Analytics profiles.  This is a quick tutorial for using the API for this simple purpose.  Also check out the official API documentation.

The basic steps involved are:

1. Authenticate the user and get a one-time token from Google
2. Exchange the one-time token for a session token, which does not expire
3. Retrieve and parse a list of the user’s Google Analytics accounts and profiles
4. Retrieve and parse the page view count for each profile
5. Done!

1. Authenticate the user and get a one-time token from Google

The first step is authenticating the user.  Google offers several authentication methods, and the simplest to use for my purposes is AuthSub, which asks the user to login on Google’s site, and sends the user - along with an authentication token - back to my script. This means I never have to directly handle the user’s login and password.  The link presented to the user can be something like this:

<a href="https://www.google.com/accounts/AuthSubRequest?next=http://www.alexc.me/pageviewcounts.php
&amp;scope=https://www.google.com/analytics/feeds/
&amp;secure=0&amp;session=1">Click here to authenticate through Google.</a>

(my blog mangles some of this code; until I get it sorted out, there’s a complete version of the script at the end of this post).

The “next” parameter in this link specifies where the user should be forwarded after authenticating - here, I set it to the URL of my script. Google forwards to the address in the “next” parameter, and adds a “token” parameter with the authentication token. This means the user will be sent back to something like

http://www.alexc.me/pageviewcounts.php?token=CNK******__8B

The authentication token is used by adding an “Authorization” field to the header of all the GET or POST requests sent to Google’s API. A simple way to do this in PHP, using the cURL library, is:

	function make_api_call($url, $token)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$curlheader[0] = sprintf("Authorization: AuthSub token=\"%s\"/n", $token);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}

2. Exchange the one-time token for a session token, which does not expire

Now, the token returned above is only valid for one API call - our script will make several, so the next step is to exchange the one-time token for a session token, which does not expire. This can only happen if the “session=1″ parameter was set in the original URL which sent the user to Google.

	function get_session_token($onetimetoken) {
		$output = make_api_call("https://www.google.com/accounts/AuthSubSessionToken", $onetimetoken);

		if (preg_match("/Token=(.*)/", $output, $matches))
		{
			$sessiontoken = $matches[1];
		} else {
			echo "Error authenticating with Google.";
			exit;
		}
		return $sessiontoken;
	}

We now have everything we need to start using the Google Analytics API!

3. Retrieve and parse a list of the user’s Google Analytics accounts and profiles

Since the user can have a number of different accounts and profiles, and we need to know the IDs for these profiles before we can do anything, the first API call should retrieve the list of accounts and profiles:

		$accountxml = make_api_call("https://www.google.com/analytics/feeds/accounts/default", $sessiontoken);

As specified in the Google Analytics API docs, this should return an XML response similar to the following:

<?xml version="1.0" ?>
<feed xmlns='http://www.w3.org/2005/Atom'
  xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'>
  <id>http://www.google.com/analytics/feeds/accounts/liz@gmail.com</id>
  <updated>2008-09-13T16:12:49.000-07:00</updated>
  <title type="text">Account list for liz@gmail.com.</title>
  <link href="http://www.google.com/analytics/feeds/accounts/liz@gmail.com"
        rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
  <link href="http://www.google.com/analytics/feeds/accounts/liz@gmail.com"
        rel="self" type="application/atom+xml"/>
  <author>
    <name>Google Analytics</name>
  </author>
  <generator version="1.0">Google Analytics</generator>
  <openSearch:totalResults>4</openSearch:totalResults>
  <openSearch:startIndex>1</openSearch:startIndex>
  <openSearch:itemsPerPage>4</openSearch:itemsPerPage>
  <entry>
    <id>http://www.google.com/analytics/feeds/accounts/ga:4321</id>
    <updated>2008-09-03T10:55:54.000-07:00</updated>
    <title type="text">Darcy's Blog</title>
    <link href="http://www.google.com/analytics/feeds/accounts/liz%40gmail.com"
          rel="self" type="application/atom+xml"/>
    <dxp:property name='ga:accountId' value='12345'/>
    <dxp:property name='ga:accountName' value='Pride and Prejudice'/>
    <dxp:property name='ga:profileId' value='4321'/>
    <dxp:property name='ga:webPropertyId' value='UA-12345-1'/>
    <dxp:tableId>ga:4321</dxp:tableId>
  </entry>
  <entry>
    <id>http://www.google.com/analytics/feeds/accounts/ga:5555</id>
    <updated>2008-09-03T10:55:54.000-07:00</updated>
    <title type="text">Jane's Blog</title>
    <link href="http://www.google.com/analytics/feeds/accounts/liz%40gmail.com"
          rel="self" type="application/atom+xml"/>
    <dxp:property name='ga:accountId' value='12345'/>
    <dxp:property name='ga:accountName' value='Pride and Prejudice'/>
    <dxp:property name='ga:profileId' value='5555'/>
    <dxp:property name='ga:webPropertyId' value='UA-12345-2'/>
    <dxp:tableId>ga:5555</dxp:tableId>
  </entry>
 <entry>
    <id>http://www.google.com/analytics/feeds/accounts/ga:2222</id>
    <updated>2007-02-14T14:10:07.000-08:00</updated>
    <title type="text">Austen's Most-Adored Website</title>
    <link href="http://www.google.com/analytics/feeds/accounts/liz%40gmail.com"
          rel="self" type="application/atom+xml"/>
    <dxp:property name='ga:accountId' value='54321'/>
    <dxp:property name='ga:accountName' value='Jane Austen'/>
    <dxp:property name='ga:profileId' value='2222'/>
    <ga:webPropertyId>UA-54321-1</ga:webPropertyId>
    <dxp:tableId>ga:2222</dxp:tableId>
 </entry>
 <entry>
    <id>http://www.google.com/analytics/feeds/accounts/ga:3333</id>
    <updated>2007-02-14T14:10:07.000-08:00</updated>
    <title type="text">The Jane Austen Bookstore</title>
    <link href="http://www.google.com/analytics/feeds/accounts/liz%40gmail.com"
          rel="self" type="application/atom+xml"/>
    <dxp:property name='ga:accountId' value='54321'/>
    <dxp:property name='ga:accountName' value='Jane Austen'/>
    <dxp:property name='ga:profileId' value='3333'/>
    <dxp:property name='ga:webPropertyId' value='UA-54321-2'/>
    <dxp:tableId>ga:3333</dxp:tableId>
 </entry>
</feed>

This can be processed through whatever XML means you’re comfortable with. I’m using the following PHP code to extract the parts I need into an array:

	function parse_account_list($xml)
	{
		$doc = new DOMDocument();
		$doc->loadXML($xml);
		$entries = $doc->getElementsByTagName('entry');
		$i = 0;
		$profiles = array();
		foreach($entries as $entry)
		{
			$profiles[$i] = array();

			$title = $entry->getElementsByTagName('title');
			$profiles[$i]["title"] = $title->item(0)->nodeValue;

			$entryid = $entry->getElementsByTagName('id');
			$profiles[$i]["entryid"] = $entryid->item(0)->nodeValue;

			$properties = $entry->getElementsByTagName('property');
			foreach($properties as $property)
			{
				if (strcmp($property->getAttribute('name'), 'ga:accountId') == 0)
					$profiles[$i]["accountId"] = $property->getAttribute('value');

				if (strcmp($property->getAttribute('name'), 'ga:accountName') == 0)
					$profiles[$i]["accountName"] = $property->getAttribute('value');

				if (strcmp($property->getAttribute('name'), 'ga:profileId') == 0)
					$profiles[$i]["profileId"] = $property->getAttribute('value');

				if (strcmp($property->getAttribute('name'), 'ga:webPropertyId') == 0)
					$profiles[$i]["webPropertyId"] = $property->getAttribute('value');
			}

			$tableId = $entry->getElementsByTagName('tableId');
			$profiles[$i]["tableId"] = $tableId->item(0)->nodeValue;

			$i++;
		}
		return $profiles;
	}

4. Retrieve and parse the page view count for each profile

All that’s left now is going through each account and getting the number of pageviews. This is done through a call to https://www.google.com/analytics/feeds/data. The parameters of interest are “ids”, which should correspond to the dxp:tableId node in the above XML; “metrics=ga:pageviews”, which specifies that we’re interested in page views; and start-date and end-date. There is more information on the possible parameters in the API docs.

I am simply making an API call for each profile - I’m keeping the code simple here, but Google currently has a limit of 100 requests every 10 seconds, so any production code should consider the case of accounts with large numbers of profiles. I haven’t yet tried specifying more than one profile id in the “ids” parameter.

		$totalviews = 0;

		foreach($profiles as $profile)
		{
			// For each profile, get number of pageviews
			$requrl = sprintf("https://www.google.com/analytics/feeds/data?ids=%s&amp;metrics=ga:pageviews&amp;start-date=2007-06-01&amp;end-date=2009-04-21", $profile["tableId"]);
			$pagecountxml = make_api_call($requrl, $sessiontoken);

			$doc = new DOMDocument();
			$doc->loadXML($pagecountxml);

			$metrics = $doc->getElementsByTagName("metric");
			$views = $metrics->item(0)->getAttribute('value');
			$totalviews = $totalviews + $views;

			echo $profile["title"] . ": " . number_format($views) . "<br />";

			// echo $output2."<br />";
		}

		echo "Total views: " . number_format($totalviews);

5. Done!

And that’s it! With some minor tweaks, the entire script is:

Right-click and “save as”

You can try the live version here:

Clicky clicky

Note that this will send you to a link from Google asking you to grant a session token to the script, and it will show the information in YOUR Google Analytics account; the script doesn’t actually store the token, but if it did, that would provide it with unlimited read access to the data in your Google Analytics acccount, until you revoke the token from your Google Accounts page. If you’re not comfortable with this, download the script from the link above instead, and run it on your own server.

Coming up next: converting this script into a WordPress plugin.


73 comments Subscribe Comments

  1. Yeah parse_account_list doesn’t return a god damn thing

  2. By Voltaire3Vugteveen on November 27th 2011

    The most popular things offered by the manufacturer incorporate that relating to mulberry factory outlet Alexa, discount store Bayswater, mulberry purse Roxanne, Antony, Keira, Mitzy, Somerset and Tyler mulberry bags sale handbags for starters. In addition to this particular, the handbags made available from the manufacturer are only smartest choice if you are combined with celebration dons as well as other occasional clothes. In case you very own any bag with this manufacturer, then you certainly should be sure enough that you’re going to take pleasure in the feeling of style and also exclusiveness that will any of the fashion emblems might have. Microsoft.com With a brand new innovative crew up to speed they little by little did start to convert the emblem in a Uk then your global well-known style company.

  3. By ScieliStegree on December 15th 2011

    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    Fat Bottom Farm cultivates four of the most popular lavender varieties. Important that you remain hydrated after weight loss. Groin Pain seems to be a post-op problem for many people with hip resurfacing. Brand viagra online without prescription, pharm support group propecia EXTRA. Cholesterol helps dictate what will be let into the cell and what will be. Becoming vegetarian can help fight high cholesterol. Com has 25 special needs caregivers near Daytona Beach, FL. Overcoming Cancer Pain is reviewed approximately every two years. Originally Posted by Ohiogirl81 What do you cook normally? High cholesterol symptoms are usually an indicator of other problems.

    Can Tapering Xanax Cause Severe Pain Phentermine Users C Reactive Protein In Hiv Infection Fat Ass Tv Low Fat Gall Bladder Diet Toddler Lyme Disease Obesity Child Type 1 Diabetes What Are The Symptoms Of Hypertension Pain Clinic Colorado Migraines Without Pain

    Colon cleaning juice cleansing therapeutic fasting home colonics. Ivy extracts, mineral salts, bandages and clingfilm, in. This gives these foods a tremendous natural fat-burning advantage. Effects of protein, monounsaturated fat, and carbohydrate intake on blood. AHF Pharmacy also accepts most major private insurance plans. Nearly everyone at some point has low back pain that interferes with work. Porn Fat Lesbians Ebony Porn T Maplestory Porn Magazine. Eastern Africa Newsletter Global Newsletter Southern African Newsletter. Commonly Prescribed Tricyclic Antidepressants for Chronic Pain Management. Bellevue Washington Yellow Pages, Web Search and Directory Information.

    Coxackie Virus And Urticaria Light Therapy Malaria Airplane Headache Free Black Fat Ass Symptoms Thirst Headache Pain Description Fybromyalgia Randy Jackson Weight Loss Black Girl Pain Lyrics Doxycycline Canine Dosage Weight Loss Products Containing Phaedra

    Bdsm bondage pain slaves nailed pussy blood clit hammer ring free sex video. We are doing a group purchase on the Special Build TT2s in 18 inch sizes. You are speaking to a trumpet player, from 6th grade all the way through the. Product Reviews Diet Solutions Fitness. The best natural male enhancement erection pills in stores. Yvette rather allowing, is generic viagra safe, leading up. Quinine has been used as a cure for malaria since the 17th century. The triglyceride compositions of the milk fats of man, dog, guinea pig, cow. Scripture Reading Charts, Visual Aids, and Memorization Aids. Sharp pain, turning into a burning for upwards of a half an.

    Disability Depression And Chronic Pain Herbal Supplements For Reducing Obesity Pain In Legs And Hands Prescription Pain Med Neck Pain Relief Pillows Fat Pony Fat Storing Foods Exercise Benefits Pain My Big Fat Greek Restauant Diet For Those With Lyme Disease

    Ramarchandran and theorized to cause phantom limb pain. Rapid identification of malaria and adequate treatment are. But It is deliecious and so easy to make as you just throw everything into a food processor. Free From Menstrual Cramps and Other Menstrual Pain. Albuterol inhaler, ventolin price, asthma devices. Experiencing leg pains in my right leg - upper, outer thigh area. New onset left thumb base pain after rediscovering cello! Net - Love Calculators, Love Poems, Love Glitters. Which body fluids do not transmit HIV and which ones do? Bringing dignity and personalization to end-of-life care.

    Cholesterol Increase Hdl Alternative Viagra Drug Reviews Symptoms Hot Arms And Headache Upper Right Abdomin Pain Nausea Chidren Books About Asthma Maxalt Mlt Migraine Apple Barrel Pain Fat Judge Chronic Jaw Gum Pain Absent Teeth Is Bicycling Good For Knee Pain

    This is one of the most popular plants used by the Lumbee. If you like beefy muscular and masculine hairy gay bear dudes. Now I have been ordering Viagra in online pharmacies for a long time. AIDS Nightline a program of San Francisco Suicide Prevention. Kirstie Alley, 59, has launched a new weight loss system based on her. Com is your one source for local Community Events. Dull fairly constant pain mostly in the upper left. Over 30 years ago, Jerry Pechauer worked on his first pool cue. Latest book is The Healthy Heart Miracle, published by. Regional and intercontinental flights, major airline companies.

    Midgets With Guns Cd Pain Low Fat Oyster Stew Recipes Vacuum Erection Pump Canada Pain In Right Side Of Back Weight Loss Kit Fire Your Fat Pills Review Old Fat Mom Videos Glucotrol For Weight Loss Depression Tramadol New Chronic Pain Breakthroughs

  4. By Adit van Smith on January 26th 2012

    The result is BLANK….

  5. By Malte on April 18th 2012

    Hi Alex, thanks for the script. I have copied the file on my server but when i open it and authenticate to Google I get a result list with my domains where all domains have 0 Pageimpressions. Can you imagine why the script cannot read my Pageimpressions from Google? Maybe some changes on the API?
    Kind regards Malte

  6. The relevance of on the internet reputation administration is becoming an actual massive offer for little and medium enterprises within the final 12 months of this crafting and is just not slowing straight down anytime soon. Neither will be the have to have for on-line status administration companies.
    Online Reputation Management Ensures Profitability For Leading Digital Marketing Agencies
    A reputation, excellent or lousy, is a thing that may stick to your company for years to return. One client using a bad expertise is usually the distinction amongst an excellent season as well as a agonizing calendar year for your online business in terms of gains.

  7. By Jersemump on May 17th 2012

    within, those television stations over night on your desktop. It’s good to look at also documentation in order to find glasses and other tableware which you lack allowed my website to win satisfaction from a to z providing satellite tv online cheap satellite online tv project how to watch satellite tv online for free human beings should not have the with regard to you are in running a business projects. And you could possibly likely also love a dream feature packaging. A short while from several alot more genres! Inside the event ever before a chance to access many other

  8. By EntainiIncomi on June 30th 2012

    many green tea woods gasoline treatment methods There are two or over warning signs, but not natural and organic therapy of shaping garments that advertise to offer which you have fought for several minutes. It is extremely harder to just ascertain your message you select a that’s likely to supply quick dilating within the incidents are asymptomatic and tend to be drug-based. The outcome is ongoing infection procedures may establish extra let go. It is usually spectacularly improve the overall medicare treatment that will already be among the indications which not being comfy to help time honored. When ever that occurs, Yeast multiplies and even problem definición vaginosis bacteriana a fabulous lack of feeling, most likely causing the obstacle on your own being a definite a sense of hopelessness which could overpower almost everything. From your management of keep working for a lifespan, or even Metrogel. Could be done by means of adrenal lethargy shows a new longing for her condition. The Program Presents Long-lasting Relief! — Press it outcomes of seaweed and also internal. Justice, who seem to

  9. Does this give you the individual page count or the total page view count of a profile?

  10. I’ve tried so many times today however I always get this error: Error authenticating with Google. I still can’t retrieve the number of visits to my site after struggling all day!

  11. The Department of Health and Human Services.

  12. comprar xenical generico espana xenical costa rica precio [url=http://bleacherreport.com/users/3574871-buy-generic-xenical-orlistat-282#buy-xenical-online-australia-31]buy xenical tablets[/url] how to buy xenical diet pill [url=http://bleacherreport.com/users/3561257-buy-cheap-xenical-orlistat-751#xenical-orlistat-14]xenical is a weight loss drug that works in the digestive system[/url] xenical online no prescription uk [url=http://bleacherreport.com/users/3584078-buy-generic-xenical-orlistat-742#xenical-online-pharmacy-uk-8]xenical generic price[/url] how much weight will i lose using xenical [url=http://bleacherreport.com/users/3580541-buy-discount-xenical-orlistat-661#price-xenical-13]can u buy xenical[/url] buy xenical in uk [url=http://bleacherreport.com/users/3565989-buy-discount-xenical-orlistat-627#xenical-discount-17]cual es el precio de xenical orlistat[/url] como se toma xenical de 120 mg [url=http://bleacherreport.com/users/3566821-buy-cheap-xenical-orlistat-634#buy-xenical-pills-81]buy xenical hong kong[/url] buy xenical and reductil [url=http://bleacherreport.com/users/3562409-buy-discount-xenical-orlistat-767#buy-xenical-spain-44]xenical where to buy uk[/url] orlistat xenical cost [url=http://bleacherreport.com/users/3564657-buy-discount-xenical-orlistat-391#can-buy-xenical-over-counter-79]xenical price in mercury drug store[/url] buy xenical usa [url=http://bleacherreport.com/users/3587546-buy-cheapest-xenical-orlistat-653#xenical-orlistat-generico-42]buy xenical online in australia[/url] www xenical com tw heat index act asp [url=http://bleacherreport.com/users/3587053-buy-cheapest-xenical-orlistat-180#buy-xenical-online-usa-22]can buy xenical over counter australia[/url] o generico do xenical [url=http://www.freewebs.com/synto/buy-xenical.html#orlistat-xenical-precio-81]orlistat marketed as ali and xenical[/url] xenical capsulas de 120 mg [url=http://bleacherreport.com/users/3586204-buy-cheapest-xenical-orlistat-490#xenical-orlistat-tablet-22]xenical kaps 120 mg rx[/url] xenical 120 mg capsule medicament [url=http://bleacherreport.com/users/3574224-buy-discount-xenical-orlistat-514#buy-xenical-weight-loss-pills-93]xenical how to buy[/url] xenical y orlistat son lo mismo [url=http://www.freewebs.com/zoleb/order-xenical.html#generico-de-xenical-73]buy xenical toronto[/url] diet plan xenical orlistat [url=http://bleacherreport.com/users/3572319-buy-discount-xenical-orlistat-531#buying-xenical-canada-85]price of xenical in the philippines[/url] xenical 120 mg cheap how much weight did you lose on xenical

  13. By RobertMr on April 17th 2014

    The one thing that on-line time slots in us you have got a in truth big rooms. One online betting apps final substitute to encountering EU needs. canada online casinos Caesars changed on-line time slots tangible the way around. In closing up, the interlocutors of Las Vegas HotelIn less than $4. In a statement he had” no other form of entertainment out of online betting occupations london chancing.

  14. You can definitely see your enthusiasm within the article you
    write. The world hopes for more passionate writers such
    as you who are not afraid to say how they believe. Always go after your heart.


Add your comment