Search code examples
phpgoogle-analyticsgoogle-analytics-apigoogle-api-php-client

Get events data from Google Analytics API with PHP


I want to get events of one of my apps that uses Google Analytics. I am little confused with example given in the official documentation. I make it work but i don't understand how to use it for my case.

require_once 'GA/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_Analytics($client);

After this code I want to get events data - how should I specify counter id, and event info?

Using Query Explorer I managed to created query that I need:

googleapis.com/analytics/v3/data/ga?ids=ga%3A111111&start-date=30daysAgo&end-date=2016-05-11&metrics=ga%3AtotalEvents&dimensions=ga%3AeventLabel

Solution

  • I am not sure what you mean by counter id. You have your analytics service you just need to make the request now.

    $params = array('dimensions' => 'ga:AeventLabel');  
    // requesting the data  
    $data = $analytics->data_ga->get("ga:89798036", "30daysAgo", "2016-05-11", "ga:totalEvents", $params );
    // displaying the data
    foreach ($data->getRows() as $row) {        
                print "ga:AeventLabel ".$row[0]." ga:totalEvents ".$row[1]";     
            }