Skip to content

Instantly share code, notes, and snippets.

@rakuishi
Created December 27, 2014 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rakuishi/f06f4cbca1e320fd6821 to your computer and use it in GitHub Desktop.
Save rakuishi/f06f4cbca1e320fd6821 to your computer and use it in GitHub Desktop.
<?php
require_once(dirname(__FILE__) . '/google-api-php-client/autoload.php');
define('APPLICATION_NAME', '*');
define('SERVICE_ACCOUNT_NAME', '*@developer.gserviceaccount.com');
define('KEY_PATH', dirname(__FILE__) . '/p12/*.p12');
date_default_timezone_set('Asia/Tokyo');
class Analytics {
private $service;
function __construct($applicationName, $serviceAccountName, $keyPath) {
$creds = new Google_Auth_AssertionCredentials(
$serviceAccountName,
array('https://www.googleapis.com/auth/analytics'),
file_get_contents($keyPath)
);
$client = new Google_Client();
$client->setApplicationName($applicationName);
$client->setAssertionCredentials($creds);
$this->service = new Google_Service_Analytics($client);
}
function getReport($viewId, $startDate, $endDate) {
$result = $this->service->data_ga->get(
'ga:' . $viewId,
$startDate,
$endDate,
'ga:pageviews,ga:users,ga:screenviews'
);
return $result['rows'];
}
}
$analytics = new Analytics(APPLICATION_NAME, SERVICE_ACCOUNT_NAME, KEY_PATH);
$viewId = '*';
$yesterday = @date('Y-m-d', strtotime('-1 day'));
var_dump($analytics->getReport($viewId, $yesterday, $yesterday));
@rakuishi
Copy link
Author

rakuishi commented Feb 6, 2015

イベントを取得する場合は、以下のように書く。

$result = $this->service->data_ga->get(
    'ga:' . $viewId,
    @date('Y-m-d', strtotime('-1 month')), // 開始日
    @date('Y-m-d'), // 終了日
    'ga:totalEvents',
    array(
        'dimensions'  => 'ga:eventAction,ga:eventLabel',
        'filters'     => 'ga:eventAction=@アクション名',
        'sort'        => '-ga:totalEvents',
        'max-results' => '10' // 件数
    )
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment