Calculating a page’s bounce rate with the Google Analytics API

I had an email a couple of days ago from someone asking me how to calculate the bounce rate for a page using my PHP Class for the Google Analytics API.

The formula supplied from Google from the “Common Calculations” section of the Analytics API documentation says the bounce rate for a particular page should be caculated like this:

ga:bounces/ga:uniquePageviews,ga:pagePath

To work this out using my PHP Class you would do something like the following example. I’ve multiplied the caculation up by 100 to give a percentage in this example.

$data = $api->data($id, 'ga:pagePath', 'ga:bounces,ga:uniquePageviews');
 foreach($data as $page_path => $row) {
 $bounce_rate = round(100 * $row['ga:bounces'] / $row['ga:uniquePageviews'], 2);
 echo "$page_path $bounce_rate%n";
 }

The round(…, 2) rounds the number to 2 decimal places (see my rounding numbers with PHP post for more details).

The above example would output the following from my own data as at the time of writing this post.

/jquery-get-set-form-values/ 87.17%
 /article/apache/restart-apache/ 94.31%
 /article/mysql/delete-all-data-mysql/ 91.23%
 /php-http-referer-variable/ 92.74%
 /check-uncheck-checkbox-jquery/ 86.73%
 /article/mysql/cross-table-update/ 88.99%
 /article/networking/open-firewall-msn-icq/ 94.37%
 /article/linux-unix-bsd/howto-check-md5-file/ 94.75%
 /upper-lower-case-strings-mysql/ 95.69%
 /install-yum-with-rpm-on-centos/ 87.36%

The defaults for the ->data() method will get data for the month to yesterday and for the first 10 records only. This can be modified to a different date range and/or number of records. For example, to get the same data for 1000 records for the same date range you could do this:

$data = $api->data($id, 'ga:pagePath', 'ga:bounces,ga:uniquePageviews', '', '', '', 1000);

I’ve realised in writing this I don’t actually have a post dedicated to the parameters for the data call so will write one and post it tomorrow.