9/15/2014 Display Top URLs With Google Analytics API (PHP) http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 1/10 Ad by GoSave (http://advertising-support.com/why.php?type=3&zone=762639&pid=1542&ext=GoSave) | Close W 11 (http://www.sa viewed- pages- with- google- analytics- api#comment Display Top URLs With Google Analytics API (PHP) e can use Core Reporting API to fetch top (Popular) URLs from Google Analytics. Using Google API PHP Client (https://code.google.com/p/google-api-php-client/downloads/list) let’s create a simple PHP page that pulls website’s top URLs from Google Analytics and updates MySql table. Once you are familiar, I am sure you can do lot more, I mean just checkout the information you can retrieve in this Reporting API (http://ga-dev-tools.appspot.com/explorer/). Let’s start by creating MySql table called google_top_pages , table contains 4 columns (id, page_uri, page_title, total_views). You can run this query in your PhpMyAdmin to have this table created. 1 2 3 4 5 6 7 CREATE TABLE IF NOT EXISTS `google_top_pages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `page_uri` varchar(60) NOT NULL, `page_title` varchar(60) NOT NULL, `total_views` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ; Configuration This is important part: 1. Create Google OAuth API Keys (http://www.sanwebe.com/2012/10/creating-google-oauth-api-key) and get Client ID and secret. 2. Enter redirect url in Google Redirect URI (http://www.sanwebe.com/2012/01/set-authorized-redirect-uris-in-google- api-console), or you will get redirect mismatch error. 3. Enable Analytics API in Google APIs Console (https://code.google.com/apis/console/)->Services Page.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
9/15/2014 Display Top URLs With Google Analytics API (PHP)
e can use Core Reporting API to fetch top (Popular) URLs from Google Analytics. Using Google APIPHP Client (https://code.google.com/p/google-api-php-client/downloads/list) let’s create a
simple PHP page that pulls website’s top URLs from Google Analytics and updates MySql table. Onceyou are familiar, I am sure you can do lot more, I mean just checkout the information you can retrievein this Reporting API (http://ga-dev-tools.appspot.com/explorer/).
Let’s start by creating MySql table called google_top_pages , table contains 4 columns (id, page_uri,page_title, total_views). You can run this query in your PhpMyAdmin to have this table created.
1234567
CREATE TABLE IF NOT EXISTS `google_top_pages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `page_uri` varchar(60) NOT NULL, `page_title` varchar(60) NOT NULL, `total_views` int(11) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
Configuration
This is important part:
1. Create Google OAuth API Keys (http://www.sanwebe.com/2012/10/creating-google-oauth-api-key) and get Client IDand secret.
2. Enter redirect url in Google Redirect URI (http://www.sanwebe.com/2012/01/set-authorized-redirect-uris-in-google-api-console), or you will get redirect mismatch error.
3. Enable Analytics API in Google APIs Console (https://code.google.com/apis/console/)->Services Page.
In Google Analytics Settings below, enter your site’s Analytics profile id like this : “ga:ProfileID”. Enter number of resultsyou want to fetch, you can play around with dimensions and metrics later and don’t forget to enter MySql details.
$mysqli = new mysqli($hostname,$db_username,$db_password,$db_name);
Updating Top Pages
If everything is set correctly in configuration file, PHP page below should run without any trouble. We can run this pageonce or twice a month to fetch top pages from Google Analytics, and store them in MySql database for later retrieval.We need to authenticate user first, and once we have the access token, we can proceed further with Analytics services.Please go though comment lines to understand the process.
//include google api filesrequire_once 'src/Google_Client.php';require_once 'src/contrib/Google_AnalyticsService.php';
$gClient = new Google_Client();$gClient->setApplicationName('Login to saaraan.com');$gClient->setClientId($google_client_id);$gClient->setClientSecret($google_client_secret);$gClient->setRedirectUri($google_redirect_url);$gClient->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));$gClient->setUseObjects(true);
//check for session variableif (isset($_SESSION["token"])) {
//set start date to previous month $start_date = date("Y-m-d", strtotime("-1 month") ); //end date as today $end_date = date("Y-m-d"); try{ //set access token $gClient->setAccessToken($_SESSION["token"]);
9/15/2014 Display Top URLs With Google Analytics API (PHP)
//create analytics services object $analyticsService = new Google_AnalyticsService($gClient); //analytics parameters (check configuration file) $params = array('dimensions' => $google_analytics_dimensions,'sort' => $google_analytics_sort_by,'filters' => 'ga:medium==organic' //get results from google analytics $results = $analyticsService->data_ga->get($google_analytics_profile_id,$start_date,$end_date, $google_analytics_metrics } catch(Exception $e){ //do we have an error? echo $e->getMessage(); //display error } $pages = array(); $rows = $results->rows; if($rows) { echo '<ul>'; foreach($rows as $row) { //prepare values for db insert $pages[] = '("'.$row[0].'","'.$row[1].'",'.$row[2].')'; //output top page link echo '<li><a href="'.$page_url_prefix.$row[0].'">'.$row[1].'</a></li>'; } echo '</ul>'; //empty table $mysqli->query("TRUNCATE TABLE google_top_pages"); //insert all new top pages in the table if($mysqli->query("INSERT INTO google_top_pages (page_uri, page_title, total_views) VALUES ".implode(',', $pages { echo '<br />Records updated...'; }else{ echo $mysqli->error; } } }else{ //authenticate user if (isset($_GET['code'])) { $gClient->authenticate(); $token = $gClient->getAccessToken(); $_SESSION["token"] = $token; header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); }else{ $gClient->authenticate(); }}
Retrieving Top URLs from DB
When the top URLs are stored in database, here’s how we can retrieve the records from database. You can display itanywhere you like, such as on the sidebar or footer of your website etc.
//link to update page for adminecho '<div class="update-button"><a href="update_pages.php">Update top pages list!</a></div>';?>
Demo
If you haven’t noticed, there’s a Highlights widget on the right sidebar of this page, that’s exactly how this script pulls thepopular links of your website.
Related Articles:Google Map v3 Editing & Saving Markers in Database – II (http://www.sanwebe.com/2013/10/google-map-v3-editing-saving-marker-in-database)
Facebook Twitter and Google Plus Fan Counts PHP (http://www.sanwebe.com/2012/11/facebook-twitter-google-plus-fan-counts)
Login with Google using PHP API library (http://www.sanwebe.com/2012/11/login-with-google-api-php)
Multi Items Payment with PayPal REST API (PHP) (http://www.sanwebe.com/2014/09/multi-items-payment-with-paypal-rest-api-php)
PayPal REST API Payment System (PHP) (http://www.sanwebe.com/2014/09/paypal-rest-api-payment-system)
11 Comments
TheodisAUGUST 31, 2014 AT 3:27 AM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-18635)
It sure would be nice to get this updated for the new library! 1.0.0 Thanks!
Matt Cooper (Http://Www.Linuxtutorial.Co.Uk)DECEMBER 8, 2013 AT 11:07 PM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-4127)
Hi,
I have followed your tutorial through and just seem to get:
(403) User does not have sufficient permissions for this profile.
Matt Cooper (Http://Www.Linuxtutorial.Co.Uk)DECEMBER 8, 2013 AT 11:15 PM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-4128)
Got it sorted Turned out I had the wrong ID in place.
Thanks for the great write up.
Matt
Shreyo (Http://Www.Ondeweb.In)OCTOBER 4, 2013 AT 10:13 AM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-3820)
what are the changes to be made for fetching individual page view/ counts? can i use =filters=ga:pagePath=’ in the api link?please help.thanks,
Ad by GoSave (http://advertising-support.com/why.php?type=3&zone=762639&pid=1542&ext=GoSave) | Close
Join 12k SubscribersEnter email address for updates.
Your Email Address Subscribe
Sanwebe is created and written by Saran Chamling, a Web enthusiast from Sikkim, India. It is built on WP (http://wordpress.org/), hosted by Dreamhost(http://www.dreamhost.com/r.cgi?1391135) and Amazon Cloud Front (https://aws.amazon.com/). Fonts by Typekit