Showing posts with label PHP GOOGLE ANALYTICS API. Show all posts
Showing posts with label PHP GOOGLE ANALYTICS API. Show all posts

Tuesday, 18 September 2018

Get data for a single page from the Google Analytics API

The Google Analytics API has a filters feature which allows you to filter the data in a variety of ways, including filtering by URL. This means that you can get specific metrics (e.g. pageviews etc) for a single page from the GA API.

Dimensions and Metrics Available

Refer to the Dimensions & Metrics Reference in the Google Analytics API documentation for a complete list and full details about the dimensions and metrics available.

Filters

Refer to the Filters section of the "Data API - Data Feed" section of the Google Analytics API documentation for complete details about filters.

The GA API request URL

When querying the Google Analytics API for just a specific URL, add a filter for ga:pagePath set to an exact match for the URL you wish to query.
At the time of writing this post the most popular page on this blog is "How to get and set form element values with jQuery" which has the page /jquery-get-set-form-values/ so I will use that as the example for the filter.
With proper escaping, an exact match == looks like %3D%3D and /jquery-get-set-form-values/ looks like %2Fjquery-get-set-form-values%2F Therefore the following would be appended to your request URL:
&filters=ga:pagePath%3D%3D%2Fjquery-get-set-form-values%2F
A full example request might look like this, where I've added linebreaks to make it more legible:
https://www.google.com/analytics/feeds/data?ids=ga:7426158
  &dimensions=ga:pagePath&metrics=ga:pageviews,ga:uniquePageviews,
  ga:bounces,ga:entrances,ga:exits,ga:newVisits,ga:timeOnPage
  &start-date=2009-06-14&end-date=2009-07-13&max-results=10
  &start-index=1&filters=ga:pagePath%3D%3D%2Fjquery-get-set-form-values%2F

Using my GA API PHP Class

If you are using my Google Analytics API PHP Class you can do the above like so:
$filters = new analytics_filters("ga:pagePath", "==", "/jquery-get-set-form-values/");
$data = $api->data($id, 'ga:pagePath', 'ga:pageviews,ga:uniquePageviews,ga:bounces,ga:entrances,ga:exits,ga:newVisits,ga:timeOnPage', '', '', '', 10, 1, $filters, true);
Doing print_r($data) on the above will show something along these lines:
Array
(
    [/jquery-get-set-form-values/] => Array
        (
            [ga:pageviews] => 5206
            [ga:uniquePageviews] => 4816
            [ga:bounces] => 4116
            [ga:entrances] => 4592
            [ga:exits] => 4572
            [ga:newVisits] => 3525
            [ga:timeOnPage] => 220224.0
        )

)
The timeOnPage metric is aggregated for all pageviews in seconds. To convert it to per pageview you'd need to do a caclulation like $data['ga:timeOnSite'] / $data['ga:pageviews'];

Other Dimensions

The dimension doesn't have to be ga:pagePath; it could be any valid dimension such as ga:keyword (to get the keywords used by visitors to reach your site, via both paid ads and through search engine results) or ga:source,ga:referralPath (the domain and path of a referring url to the page).

Related posts:

Using filters with the Google Analytics API and PHP

The Google Analytics API allows filtering to be done on the result data before it is fetched so you could, for example, only get data for visitors from the United States. This post shows how to format the filters field in PHP and also how to use my Google Analytics API PHP Class with filters.
Read more about my Google Analytics API PHP Class.
A URL making a request to the API looks like this, where data is being fetched for the ga:vists and ga:pageviews dimensions for the period from 2009-04-29 to 2009-05-28 (I've broken the URL onto multiple lines for readability):
https://www.google.com/analytics/feeds/data?ids=ga:7426158
    &dimensions=&metrics=ga:visits,ga:pageviews
    &sort=-ga:visits,ga:pageviews&start-date=2009-04-29
    &end-date=2009-05-28&max-results=10&start-index=1
To filter this so it only contains data for the United States add the following "filters" parameter to the request URL:
&filters=ga:country%3D%3DUnited+States
The %3D%3D is the urlencoded version of == which tells the GA API to make an exact match. Some other possible matches are != to not match the string, =~ for regular expressions, and =@ where the data contains the string. For a full list of filtering types read the documentation.
To make sure the filters are correctly formatted when using PHP use the urlencode() function. If this is not used then the GA API will return a 400 error status because it cannot understand the data passed.
An example of encoding the country filter used above would be like this in PHP:
$filters = "&filters=" . urlencode("ga:country==United States");
Using my PHP Class you could pass 'urlencode("ga:country==United States")' as the $filters parameter like so:
$data = $api->data($id, '', 'ga:visits,ga:pageviews', false, 
    false, false, 10, 1, urlencode("ga:country==United States"));
Another way to do this is to use my analytics_filters helper class which is in the same library file as the analytics class itself. You would then do something like this:
$filters = new analytics_filters('ga:country', '==', 'United States');
$data = $api->data($id, '', 'ga:visits,ga:pageviews', false, false, false, 10, 1, $filters);
If you wanted to find e.g. the data for Firefox users in the United States you would do this:
$filters = new analytics_filters('ga:country', '==', 'United States');
$filters->add_and('ga:browser', '=@', 'Firefox');
$data = $api->data($id, '', 'ga:visits,ga:pageviews', false, false, false, 10, 1, $filters);
If you wanted to find e.g. the data for visitors who have come from the United States or from Canada you would do this:
$filters = new analytics_filters('ga:country', '==', 'United States');
$filters->add_or('ga:country', '==', 'Canada');
$data = $api->data($id, '', 'ga:visits,ga:pageviews', false, false, false, 10, 1, $filters);

Related posts:

Google Analytics API PHP Class - Get most popular pages

The following shows example usage to get the most popular pages from Google Analytics using my PHP class for the GA API.
Calling the ->data() method without supplying the to and from dates will get data for the last month. $id is the profile id which is in the format ga:12345
$api->login($login, $password);
$data = $api->data($id, 'ga:pagePath', 'ga:pageviews,ga:uniquePageviews');
print_r($data);
Some example output for the above is as follows:
Array
(
    [/jquery-get-set-form-values/] => Array
        (
            [ga:pageviews] => 4451
            [ga:uniquePageviews] => 4130
        )

    [/google-analytics-api-and-php/] => Array
        (
            [ga:pageviews] => 3733
            [ga:uniquePageviews] => 2210
        )

    [/article/apache/restart-apache/] => Array
        (
            [ga:pageviews] => 3248
            [ga:uniquePageviews] => 3098
        )

    [/article/mysql/delete-all-data-mysql/] => Array
        (
            [ga:pageviews] => 2954
            [ga:uniquePageviews] => 2815
        )

    [/php-http-referer-variable/] => Array
        (
            [ga:pageviews] => 2822
            [ga:uniquePageviews] => 2660
        )

    [/check-uncheck-checkbox-jquery/] => Array
        (
            [ga:pageviews] => 2664
            [ga:uniquePageviews] => 2392
        )

    [/article/mysql/cross-table-update/] => Array
        (
            [ga:pageviews] => 2410
            [ga:uniquePageviews] => 2247
        )

    [/article/networking/open-firewall-msn-icq/] => Array
        (
            [ga:pageviews] => 2090
            [ga:uniquePageviews] => 1975
        )

    [/article/linux-unix-bsd/howto-check-md5-file/] => Array
        (
            [ga:pageviews] => 2064
            [ga:uniquePageviews] => 1994
        )

    [/mysql-find-records-in-one-table-not-in-another-revised/] => Array
        (
            [ga:pageviews] => 2023
            [ga:uniquePageviews] => 1927
        )

)
You could instead loop through the data like so:
$api->login($login, $password);
$data = $api->data($id, 'ga:pagePath', 'ga:pageviews,ga:uniquePageviews');
foreach($data as $dimension => $metrics) {
 echo "$dimension pageviews: {$metrics['ga:pageviews']} unique pageviews: {$metrics['ga:uniquePageviews']}\n";
}
Using the same example data, this would output:
/jquery-get-set-form-values/ pageviews: 4451 unique pageviews: 4130
/google-analytics-api-and-php/ pageviews: 3733 unique pageviews: 2210
/article/apache/restart-apache/ pageviews: 3248 unique pageviews: 3098
/article/mysql/delete-all-data-mysql/ pageviews: 2954 unique pageviews: 2815
/php-http-referer-variable/ pageviews: 2822 unique pageviews: 2660
/check-uncheck-checkbox-jquery/ pageviews: 2664 unique pageviews: 2392
/article/mysql/cross-table-update/ pageviews: 2410 unique pageviews: 2247
/article/networking/open-firewall-msn-icq/ pageviews: 2090 unique pageviews: 1975
/article/linux-unix-bsd/howto-check-md5-file/ pageviews: 2064 unique pageviews: 1994
/mysql-find-records-in-one-table-not-in-another-revised/ pageviews: 2023 unique pageviews: 1927
For more examples and to download my class refer to The Google Analytics API and PHP: A series

Related posts:

Wednesday, 12 September 2018

The Google Analytics API and PHP: A series

The Google Analytics API is a powerful tool for accessing analytics data without having to log into the web interface and means you can easily have automated processes for collating data and saving it to a database, emailing information on a daily basis etc.

Google Analytics API PHP Class

I have created a PHP class for accessing the Google Analytics API with CURL and using DOMDocument to parse the XML. The resulting class and example script can be downloaded here and there are a number of posts on this website showing how to use it.


Please note: This API is no longer under development and is not supported.

Try this page and this page over at Google code for other PHP APIs. For some reason Stig Manning's is the only one listed on the second page so check the first page as well because there are a couple more there as well.

Code Reuse

Feel free to use the class as you wish but if re-posting it on other websites or using it in your own projects or for your customers, please retain the notice in the analytics class file attributing the original work to me.

GA API Introductory Posts

The following posts cover a couple of things about the Google Analytics API:

Code examples

The following code examples have been posted for using the Analytics class:

Code updates

Whenever I make changes to the class I upload and add a post about what was changed.
The April 30th 2009 update included adding error triggers on request failures, and some changes to solve connection issues from Windows.
The May 22nd 2009 update included making the auth property public; adding start and end parameters to the ->data() method for "today", "yesterday" and "week"; adding the filters and debug parameter to the data method; and adding the get_summary, get_summaries and sec2hms methods.
The May 28th 2009 update included a new analytics_filters class for helping with setting up filters when calling the ->data() method.

Questions and answers

I've had various questions from people by email and answered them both in emails and by posting answers up in new blog posts.
The first Q&A post looked at possible reasons for not being able to connect to the Google Analytics API.
The second Q&A post looked at how to get the account name with a profile_ID, how to format timeOnSite, and how to get "absolute unique visitors".
The  third Q&A post looked at the badly formatted request to the Google Analytics API error, default dates and that a second instance of the API is unauthorized.