Sie sind auf Seite 1von 10

9/15/2014

Display Top URLs With Google Analytics API (PHP)

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

Display Top URLs With Google Analytics API (PHP)

| Close Display Top URLs With Google Analytics API (PHP)  11 (http://www.s viewed- pages- with-

11

(http://www.s

viewed-

pages-

with-

google-

analytics-

api#comment

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

CREATE TABLE IF NOT EXISTS `google_top_pages` (

2

`id` int(11) NOT NULL AUTO_INCREMENT,

3

`page_uri` varchar(60) NOT NULL,

4

`page_title` varchar(60) NOT NULL,

5

`total_views` int(11) NOT NULL,

6

PRIMARY KEY (`id`)

7

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;

Configuration

This is important part:

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)

In Google Analytics Settings below, enter your site’s 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 don’t forget to enter MySql details.

1

<?php

2

########## Google Settings

Client ID, Client Secret #############

3

$google_client_id

= '12345678901112.apps.googleusercontent.com';

4

$google_client_secret

= 'XYZ_1234_abcdXYZ';

5

$google_redirect_url

= 'http://yoursite.com/update_pages.php';

6

$page_url_prefix

= 'http://www.sanwebe.com';

7

 

8

########## Google analytics Settings

#############

9

$google_analytics_profile_id

= 'ga:123456'; //Analytics site Profile ID

10

$google_analytics_dimensions

= 'ga:landingPagePath,ga:pageTitle'; //no change needed (optional)

11

$google_analytics_metrics

= 'ga:pageviews'; //no change needed (optional)

12

$google_analytics_sort_by

= '-ga:pageviews'; //no change needed (optional)

13

$google_analytics_max_results

= '20'; //no change needed (optional)

14

 

15

########## MySql details #############

16

$db_username

= "db_user_name"; //Database Username

17

$db_password

= "xxxxxx"; //Database Password

18

$hostname

= "localhost"; //Mysql Hostname

19

$db_name

= 'xxxxxx'; //Database Name

20

###################################################################

21

22

$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

<?php

2

//start session

3

session_start();

4

5

//include configuration file

6

include_once("config.php");

7

8

//include google api files

9

require_once 'src/Google_Client.php';

10

require_once 'src/contrib/Google_AnalyticsService.php';

11

12

$gClient = new Google_Client();

13

$gClient->setApplicationName('Login to saaraan.com');

14

$gClient->setClientId($google_client_id);

15

$gClient->setClientSecret($google_client_secret);

16

$gClient->setRedirectUri($google_redirect_url);

17

$gClient->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

18

$gClient->setUseObjects(true);

19

20

21

//check for session variable

22

if (isset($_SESSION["token"])) {

23

24

//set start date to previous month

25

$start_date = date("Y-m-d", strtotime("-1 month") );

26

27

//end date as today

28

$end_date = date("Y-m-d");

29

30

try{

31

//set access token

32

$gClient->setAccessToken($_SESSION["token"]);

9/15/2014

Display Top URLs With Google Analytics API (PHP)

33

 

34

 

//create analytics services object

35

$analyticsService = new Google_AnalyticsService($gClient);

36

 

37

 

//analytics parameters (check configuration file)

38

$params = array('dimensions' => $google_analytics_dimensions,'sort' => $google_analytics_sort_by,'filter

39

 

40

 

//get results from google analytics

41

$results = $analyticsService->data_ga->get($google_analytics_profile_id,$start_date,$end_date, $google_a

42

}

43

catch(Exception $e){ //do we have an error?

44

 

echo $e->getMessage(); //display error

45

}

46

47

$pages = array();

 

48

$rows = $results->rows;

49

50

if($rows)

 

51

{

52

 

echo '<ul>';

53

 

foreach($rows as $row)

54

{

55

//prepare values for db insert

56

$pages[] = '("'.$row[0].'","'.$row[1].'",'.$row[2].')';

57

 

58

 

//output top page link

59

echo '<li><a href="'.$page_url_prefix.$row[0].'">'.$row[1].'</a></li>';

60

}

61

 

echo '</ul>';

62

 

63

 

//empty table

64

 

$mysqli->query("TRUNCATE TABLE google_top_pages");

65

 

66

 

//insert all new top pages in the table

67

if($mysqli->query("INSERT INTO google_top_pages (page_uri, page_title, total_views) VALUES ".implode(','

68

{

69

echo '<br />Records updated

';

70

}else{

71

echo $mysqli->error;

72

}

73

}

74

75

}else{

76

//authenticate user

 

77

if (isset($_GET['code'])) {

78

 

$gClient->authenticate();

79

$token = $gClient->getAccessToken();

80

$_SESSION["token"] = $token;

81

header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));

82

}else{

 

83

 

$gClient->authenticate();

84

}

85

}

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 it anywhere you like, such as on the sidebar or footer of your website etc.

1

<?php

2

//include configuration file

3

include_once("config.php");

4

5

//get all records from db table

6

$results = $mysqli->query("SELECT page_uri, page_title, total_views FROM google_top_pages ORDER BY total_views A

7

8

//list all top pages on screen

9

echo '<ul class="page_result">';

9/15/2014

Display Top URLs With Google Analytics API (PHP)

10

while($row = mysqli_fetch_array($results))

11

{

12

echo '<li><a href="'.$page_url_prefix.$row['page_uri'].'">'.$row['page_title'].'</a></li>';

13

}

14

echo '</ul>';

15

16

//link to update page for admin

17

echo '<div class="update-button"><a href="update_pages.php">Update top pages list!</a></div>';

18

?>

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 the popular links of your website.

Related Articles:

Related Articles: Google Map v3 Editing & Saving Markers in Database –

11 Comments

Add Comment

Theodis

It sure would be nice to get this updated for the new library! 1.0.0 Thanks!

Meet

thats place where im getting stuck ::

1

$rows = $results-&gt;rows;

2

if($rows)

3

{

9/15/2014

Display Top URLs With Google Analytics API (PHP)

4 echo 'c';

//thats i put just for testing that im in that loop or not

not

even any error

help

me

5 // i am not getting anything in output

Akram

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

Which one, left, right, top ? Thanks

Hi,

I have followed your tutorial through and just seem to get:

(403) User does not have sufficient permissions for this profile.

9/15/2014

Display Top URLs With Google Analytics API (PHP)

Can you offer any advice please?

Thanks, Matt

Gustavo

If I don’t want use a redirect uri?

tks

Name *

Email *

Website

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

POST COMMENT
POST COMMENT

Confirm you are NOT a spammer

used. ) POST COMMENT Confirm you are NOT a spammer Add Reply Notify me of followup

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

commenting.

9/15/2014

Display Top URLs With Google Analytics API (PHP)

You May Like

Top URLs With Google Analytics API (PHP) You May Like Others tried it and loved it
eng) Married man arrested for bringing three young kids to
eng) Married man arrested for bringing three young kids to
eng) Married man arrested for bringing three young kids to
eng) Married man arrested for bringing three young kids to

X

Brought By GoSave

You May Like

eng) eng) X Brought By GoSave You May Like Strange men and women cuddle at the
b2867.html#s-eng) Woman delivers her own baby on city bus (video) BWNToday
b2881.html#s-eng) The Breast Milk Baby now on sale at U.S. retailers BWNToday
Eagle snatches little kid playing in park (video) BWNToday

X

Brought By GoSave

9/15/2014

Display Top URLs With Google Analytics API (PHP)

9/15/2014 Display Top URLs With Google Analytics API (PHP) Ad by GoSave (http://advertising-support.com/why.php?

Join 12k Subscribers

Enter email address for updates.

Your Email Address

Subscribe

email address for updates. Your Email Address Subscribe Sanwebe is created and written by Saran Chamling,
Follow Follow Follow
Follow
Follow
Follow
. Fonts by Typekit Follow Follow Follow (http://stats.buysellads .com/click.go? Advertise Here
Follow Follow (http://stats.buysellads .com/click.go? Advertise Here (https://buysellads.co
Follow Follow (http://stats.buysellads .com/click.go? Advertise Here (https://buysellads.co

Highlights

Highlights Ad by GoSave (http://advertising-support.com/why.php?

9/15/2014

Display Top URLs With Google Analytics API (PHP)

9/15/2014

Display Top URLs With Google Analytics API (PHP)