How to Get Page Views of a Site using Google Analytics Data

By | 24 th Nov 2017 | 2 min read

Google Analytics is a web analytics service provided by Google which tracks and reports website traffic. This is most widely used now. Continue reading the article for how to get the number of page views of your website using google analytics data.

Getting the google analytics data

To get some Google Analytics data for example the number of page views (API V3) first we should connect to API with the following code:

$ga_token = "some_token";
$client = new Google_Client();
$client->setApplicationName("***");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($developer_key);
$client->setScopes(array("https://www.googleapis.com/auth/analytics.readonly"));
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
$client->setAccessToken($ga_token);

Then we take all accounts with their respective profiles (views):

$service = new Google_Service_Analytics($client);               
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
$profiles = new stdClass();
foreach ($accounts->getItems() as $item) {
  foreach($item->getWebProperties() as $wp) {  
    $views = $wp->getProfiles();
    if (!is_null($views)) {
      foreach($wp->getProfiles() as $view) {
        $profiles->{$view['id']} = $view['name']; //get all the profiles
      }
    }
  }
}

Then we are going to check the page visits of page '/yourwebsite-path' in the site: "www.yourwebsite.com".

$path = "/yourwebsite-path";
$host = "www.yourwebsite.com";
// this is the default params used for google analytics api call.
$optParams = array(
    'dimensions' => 'ga:pagePath,ga:source,ga:keyword',
    'sort' => '-ga:sessions,ga:source',
    'filters' => 'ga:medium==organic,ga:pagePath=='.$path.',ga:hostname=='.$host,
    'max-results' => '25'
);
$totalSessions = 0;
//set the time period from today to one month back
$today = date('Y-m-d', time());
$monthbefore = date('Y-m-d', (time() - (30 * 24 * 60 * 60)));
foreach ($profiles as $profile_id => $profile) {
  $data = $service->data_ga->get(
            "ga:".$profile_id,
            $monthbefore,
            $today,
            'ga:sessions',  // here rather than session we can use parameter 'ga:visits' to the page visits
            $optParams
         );
 print_r($data); // here you will get the analytics data for each profile.
}