その他サービス/GoogleAnalytics/php
提供: 初心者エンジニアの簡易メモ
analyticsをphpで操作
プロジェクト作成
- https://console.developers.google.com/project
- "sample-analytics"などと入れる
認証作成
- 作成したプロジェクトを選択
- 認証情報リンクを選択
- 新しいクライアントIDを作成ボタンを押す
- サービスアカウントを選択
- 秘密鍵のjsonファイルを保存
- p12ファイルも保存
analyticsAPIを有効に
- APIリンクを選択
- AnalyticsAPIを選択
- 有効にするボタンを押す
analyticsサイト側設定
- アナリティクス設定リンクを押す
- プロパティのユーザ管理を押す
- メールアドレス欄にjsonファイル内のclient_email文字列を追加
- ビュー設定のビューIDをメモしておく
phpライブラリDL
git clone https://github.com/google/google-api-php-client.git
サンプル
require_once __DIR__ . "/google-api-php-client/src/Google/autoload.php";
define('CLIENT_ID', 'xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
define('SERVICE_ACCOUNT_NAME', 'xxxxxxxxx-xxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com');
define('KEY_FILE', __DIR__ . '/sample-analytics-xxxxxxxxxxx.p12');
// ビューIDを入力
define('PROFILE_ID', 'xxxxxxxxxx');
$client = new Google_Client();
$client->setApplicationName("Google Analytics PHP Starter Application");
$client->setClientId(CLIENT_ID);
$client->setAssertionCredentials(new Google_Auth_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/analytics'),
@file_get_contents(KEY_FILE)
));
$today = date("Y-m-d");
$lastMonth = date("Y-m-d", strtotime("-1 month"));
$service = new Google_Service_Analytics($client);
$result = $service->data_ga->get(
'ga:' . PROFILE_ID,
$lastMonth, //開始日
$today, //終了日
'ga:pageviews',
array(
'dimensions' => 'ga:pageTitle,ga:pagePath',
'sort' => '-ga:pageviews',
'max-results' => '10' //件数
)
);
print_r($result['rows']);
