「その他サービス/GoogleAnalytics/php」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→サンプル) |
(→Top10表示) |
||
| 行45: | 行45: | ||
$today = date("Y-m-d"); | $today = date("Y-m-d"); | ||
$lastMonth = date("Y-m-d", strtotime("-1 month")); | $lastMonth = date("Y-m-d", strtotime("-1 month")); | ||
| − | $ | + | $analytics = new Google_Service_Analytics($client); |
| − | $result = $ | + | $result = $analytics->data_ga->get( |
'ga:' . PROFILE_ID, | 'ga:' . PROFILE_ID, | ||
$lastMonth, //開始日 | $lastMonth, //開始日 | ||
2015年6月12日 (金) 07:56時点における版
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
Top10表示
<?php
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"));
$analytics = new Google_Service_Analytics($client);
$result = $analytics->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']);
