Display Top URLs With Google Analytics API (PHP)

10
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.

Transcript of Display Top URLs With Google Analytics API (PHP)

Page 1: Display Top URLs With Google Analytics API (PHP)

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.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api#comments)

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.

Page 2: Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP)

http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 2/10

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.

12345678910111213141516171819202122

<?php########## Google Settings.. Client ID, Client Secret #############$google_client_id = '12345678901112.apps.googleusercontent.com';$google_client_secret = 'XYZ_1234_abcdXYZ';$google_redirect_url = 'http://yoursite.com/update_pages.php';$page_url_prefix = 'http://www.sanwebe.com';

########## Google analytics Settings.. #############$google_analytics_profile_id = 'ga:123456'; //Analytics site Profile ID$google_analytics_dimensions = 'ga:landingPagePath,ga:pageTitle'; //no change needed (optional)$google_analytics_metrics = 'ga:pageviews'; //no change needed (optional)$google_analytics_sort_by = '-ga:pageviews'; //no change needed (optional)$google_analytics_max_results = '20'; //no change needed (optional)

########## MySql details #############$db_username = "db_user_name"; //Database Username$db_password = "xxxxxx"; //Database Password$hostname = "localhost"; //Mysql Hostname$db_name = 'xxxxxx'; //Database Name###################################################################

$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.

1234567891011121314151617181920212223242526272829303132

<?php//start sessionsession_start();

//include configuration fileinclude_once("config.php");

//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"]);

Page 3: Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP)

http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 3/10

3334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485

//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.

123456789

<?php//include configuration fileinclude_once("config.php");

//get all records from db table$results = $mysqli->query("SELECT page_uri, page_title, total_views FROM google_top_pages ORDER BY total_views ASC");

//list all top pages on screenecho '<ul class="page_result">';

Page 4: Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP)

http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 4/10

Add Comment

101112131415161718

while($row = mysqli_fetch_array($results)){ echo '<li><a href="'.$page_url_prefix.$row['page_uri'].'">'.$row['page_title'].'</a></li>';}echo '</ul>';

//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.

DOWNLOAD (HTTP://WWW.SANWEBE.COM/DOWNLOADS/51-GOOGLE-ANALYTICS-TOP-URLS)

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!

(/2013/05/top-viewed-pages-with-google-analytics-api?replytocom=18635#respond)

MeetMARCH 25, 2014 AT 8:42 AM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-6324)

thats place where im getting stuck ::

123

$rows = $results-&gt;rows; if($rows) {

Add Reply

Page 5: Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP)

http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 5/10

45

echo 'c'; //thats i put just for testing that im in that loop or not// i am not getting anything in output....not even any error......help me

(/2013/05/top-viewed-pages-with-google-analytics-api?replytocom=6324#respond)

MeetMARCH 25, 2014 AT 8:45 AM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-6325)

i needed a script to get google search for some of my keywords and top 10 result of that search i want…..

can you help me regarding this ?

Thank You…..

AkramFEBRUARY 26, 2014 AT 2:24 PM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-5706)

DemoIf you haven’t noticed, there’s a Popular Page widget on the sidebar of this page.

Which one, left, right, top ?Thanks

(/2013/05/top-viewed-pages-with-google-analytics-api?replytocom=5706#respond)

Saran (Http://Www.Sanwebe.Com)FEBRUARY 26, 2014 AT 3:06 PM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-5707)

Sorry, I was talking about “Highlights” widget on the right side. It was “Popular pages” earlier, I apologize for that.

AkramFEBRUARY 26, 2014 AT 8:33 PM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-5710)

Thank you, I appreciate.

GauravFEBRUARY 14, 2014 AT 3:55 AM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-5604)

can u suggest what name give two send ,third code and how to check the results

(/2013/05/top-viewed-pages-with-google-analytics-api?replytocom=5604#respond)

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.

Add Reply

Add Reply

Add Reply

Page 6: Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP)

http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 6/10

Name * Email * Website

Use Gravatar (http://gravatar.com/) for Comment Pic | Start a topic (http://www.sanwebe.com/forums/forum/general-

discussions) for crucial discussion.

Comment (Basic HTML tags like <b>, <a>, <i>, <code> can be used. )

POST COMMENT

Confirm you are NOT a spammer

Notify me of followup comments via e-mail. You can also subscribe (http://www.sanwebe.com/?page_id=99999&srp=2834&sra=s) without

commenting.

Can you offer any advice please?

Thanks, Matt

(/2013/05/top-viewed-pages-with-google-analytics-api?replytocom=4127#respond)

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,

(/2013/05/top-viewed-pages-with-google-analytics-api?replytocom=3820#respond)

GustavoSEPTEMBER 25, 2013 AT 2:22 PM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-3791)

If I don’t want use a redirect uri?

tks

(/2013/05/top-viewed-pages-with-google-analytics-api?replytocom=3791#respond)

Add Reply

Add Reply

Add Reply

Page 7: Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP)

http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 7/10

Brought By GoSave

Glispa(javascript:void(0);)

Others tried it andloved it

BWNToday(http://www.breakingworldnewstoday.com/2014/06/27-b2881.html#s-eng)

Woman deliversher own baby oncity bus (video)

BWNToday(http://www.breakingworldnewstoday.com/2014/03/b2598.html#s-eng)

The Breast MilkBaby now on saleat U.S. retailers

BWNToday(http://www.breakingworldnewstoday.com/2014/07/21-b2925.html#s-eng)

Eagle snatcheslittle kid playing inpark (video)

BWNToday(http://www.breakingworldnewstoday.com/2014/04/b2663.html#s-eng)

105-year-oldwoman getsaccepted intopreschool

BWNToday(http://www.breakingworldnewstoday.com/2014/07/18-b2918.html#s-eng)

Married manarrested forbringing threeyoung kids toprostitute BWNToday

(http://www.breakingworldnewstoday.com/2014/03/b2622.html#s-eng)

Judge orderswoman to hold "Istole from a 9 yearold" sign BWNToday

(http://www.breakingworldnewstoday.com/2014/03/b2571.html#s-eng)

Man sued aftertattooing fecesscene on girlfriend

BWNToday(http://www.breakingworldnewstoday.com/2014/04/b2650.html#s-eng)

Man arrested forfeeding sausage topolice horse Glispa

(javascript:void(0);)

You should checkthis out

Ad by GoSave (http://advertising-support.com/why.php?type=3&zone=762639&pid=1542&ext=GoSave) | Close

Brought By GoSave

BWNToday (http://www.breakingworldnewstoday.com/2014/06/24-b2867.html#s-eng)

Strange men and women cuddle at the cuddling workshop (video)BWNToday (http://www.breakingworldnewstoday.com/2014/06/27-b2881.html#s-eng)

Woman delivers her own baby on city bus (video)

BWNToday

(http://www.breakingworldnewstoday.com/2014/03/b2598.html#s-eng)

The Breast Milk Baby now on sale at U.S. retailers

BWNToday (http://www.breakingworldnewstoday.com/2014/07/21-b2925.html#s-eng)

Eagle snatches little kid playing in park (video)

You May LikeX

You May Like X

Page 8: Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP)

http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 8/10

Follow Follow Follow

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

(http://stats.buysellads.com/click.go?z=1289305&b=3978872&g=&s=&sw=1366&sh=768&br=chrome,37,win&r=0.5988178700208664&link=http://www.a2hosting.com/wordpress-hosting?utm_source=sanwebe.com&utm_medium=cpm&utm_content=&utm_campaign=)

(http://stats.buysellads.com/click.go?z=1289305&b=4926553&g=&s=&sw=1366&sh=768&br=chrome,37,win&r=0.2365661959629506&link=http://www.shazadmirza.com)

(http://stats.buysellads.com/click.go?z=1289305&b=4948293&g=&s=&sw=1366&sh=768&br=chrome,37,win&r=0.5902747996151447&link=http://gourl.io)

Advertise Here

(https://buysellads.com/buy/detail/167555/zone/1289305?

utm_source=site_167555&utm_medium=website&utm_campaign=adhere&utm_content=zone_1289305)

Highlights

Ad by GoSave (http://advertising-support.com/why.php?type=3&zone=762639&pid=1542&ext=GoSave) | Close

30 Pure CSS3 Tutorials & Examples (http://www.sanwebe.com/2012/08/pure-css3-tutorials-examples)

Page 9: Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP)

http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 9/10

Page 10: Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP)

http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 10/10