GAPIを使う
https://code.google.com/p/gapi-google-analytics-php-interface/
Googleが提供しているライブラリのページには
https://developers.google.com/analytics/devguides/reporting/core/v3/gdataLibraries
(beta)と書かれているのと、ここにはOauthを使うサンプルが書かれているが、
ブラウザは使わずにデータを取得したいのでGAPIを使う。
備考
・アカウントのID等の情報は、Spycを使ってYAMLで読み込んでいる
https://github.com/mustangostang/spyc/
下記は、前の月の特定のページ(/items/以下)のユニークページビューを多い順に20件取得、
ページタイトルと一緒に表示するサンプル。
get_unique_pageview.php
<?php
include('spyc-master/spyc.php');
include('gapi-1.3/gapi.class.php');
// 設定読み込み
$myconf = Spyc::YAMLLoad('conf.yml');
// 日付の設定
$date = new DateTime();
// 先月の初め
$last = new DateTime($date->format(‘Y-m-01’));
$last->modify(“-1 month”);
$startDate = $last->format(‘Y-m-d’);
// 先月の終わり
$last->modify(“+1 month”);
$last->modify(“-1 day”);
$endDate = $last->format(‘Y-m-d’);
$filter = ‘pagePath =~ ^/items/’;
$startIndex = 1;
$maxResults = 20;
$ga = new gapi(
$myconf\[‘ga’\]\[‘google_id’\],
$myconf\[‘ga’\]\[‘google_pw’\]
);
$ga->requestReportData(
$myconf\[‘ga’\]\[‘profile_id’\],
array(‘pagePath’, ‘pageTitle’),
array(‘uniquePageviews’),
‘-uniquePageviews’,
$filter,
$startDate,
$endDate,
$startIndex,
$maxResults
);
foreach($ga->getResults() as $result)
{
echo ‘Title: ‘ . $result->getPageTitle() . ‘ ‘;
echo ‘PagePath: ‘ . $result->getPagePath() . ‘ ‘;
echo ‘Pageviews: ‘ . $result->getUniquePageviews() . ‘ ‘;
}
conf.yml
ga:
google_id : メールアドレスを記入
google_pw : パスワードを記入
profile_id : プロファイルIDを記入 (XXXXXXXX)
参考
各言語 ライブラリ一覧
Core Reporting API Client Libraries & Sample Code (v3)
https://developers.google.com/analytics/devguides/reporting/core/v3/gdataLibraries