Sunteți pe pagina 1din 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.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 API
PHP Client (https://code.google.com/p/google-api-php-client/downloads/list) lets create a
simple PHP page that pulls websites 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/).
Lets 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.

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 sites Analytics profile id like this : ga:ProfileID. Enter number of results
you want to fetch, you can play around with dimensions and metrics later and dont forget to enter MySql details.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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 page
once 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
//start session
session_start();
//include configuration file
include_once("config.php");
//include google api files
require_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 variable
if (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)
http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api 3/10
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

//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, heres how we can retrieve the records from database. You can display it
anywhere you like, such as on the sidebar or footer of your website etc.
1
2
3
4
5
6
7
8
9
<?php
//include configuration file
include_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 screen
echo '<ul class="page_result">';

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
10
11
12
13
14
15
16
17
18
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 admin
echo '<div class="update-button"><a href="update_pages.php">Update top pages list!</a></div>';
?>
Demo
If you havent noticed, theres a Highlights widget on the right sidebar of this page, thats exactly how this script pulls the
popular 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
Theodis
AUGUST 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)
Meet
MARCH 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 ::
1
2
3
$rows = $results-&gt;rows;
if($rows)
{

Add Reply
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
4
5
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)
Meet
MARCH 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..
Akram
FEBRUARY 26, 2014 AT 2:24 PM (http://www.sanwebe.com/2013/05/top-viewed-pages-with-google-analytics-api/comment-page-1#comment-5706)
Demo
If you havent noticed, theres 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.
Akram
FEBRUARY 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.
Gaurav
FEBRUARY 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
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)
Gustavo
SEPTEMBER 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 dont want use a redirect uri?
tks
(/2013/05/top-viewed-pages-with-google-analytics-api?replytocom=3791#respond)
Add Reply
Add Reply
Add Reply
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 and
loved it
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)
BWNToday
(http://www.breakingworldnewstoday.com/2014/04/b2663.html#s-
eng)
105-year-old
woman gets
accepted into
preschool
BWNToday
(http://www.breakingworldnewstoday.com/2014/07/18-
b2918.html#s-eng)
Married man
arrested for
bringing three
young kids to
prostitute BWNToday
(http://www.breakingworldnewstoday.com/2014/03/b2622.html#s-
eng)
Judge orders
woman to hold "I
stole from a 9 year
old" sign BWNToday
(http://www.breakingworldnewstoday.com/2014/03/b2571.html#s-
eng)
Man sued after
tattooing feces
scene on girlfriend
BWNToday
(http://www.breakingworldnewstoday.com/2014/04/b2650.html#s-
eng)
Man arrested for
feeding sausage to
police horse
Glispa
(javascript:void(0);)
You should check
this 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 Like
X
You May Like
X
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 Subscribers
Enter 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)
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
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

S-ar putea să vă placă și