1. Google Dev ConsoleでAnalytics APIを有効にします。

認証情報を作成

– サービスアカウントの作成
L p12の秘密鍵を作成
– Google analyticsの対象のサービスに権限の追加でコンソールで作成したメールアドレスを追加
L 項目は表示と分析
$ git clone -b v1-master https://github.com/google/google-api-php-client.git
app.php
require_once 'google-api-php-client/src/Google/autoload.php';
$service_account_email = 'myapp-***@analytics-hoge.iam.gserviceaccount.com';
$key = file_get_contents('analytics-fugafuga.p12');
$profile = '***';
$client = new Google_Client();
$analytics = new Google_Service_Analytics($client);
$cred = new Google_Auth_AssertionCredentials(
$service_account_email,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()){
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$result = $analytics->data_ga->get(
'ga:' . $profile,
'7daysAgo',
'yesterday',
'ga:sessions,ga:pageviews'
);
echo $result -> rows[0][0] . "\n";
echo $result -> rows[0][1] . "\n";
$ php app.php
*****
*****
人気記事の取得も配列を使ってできるようです。
なるほど、割と簡単に実装できますね。