「その他サービス/GoogleAnalytics/php」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→リアルタイム数を取得) |
|||
| 行60: | 行60: | ||
==リアルタイム数を取得== | ==リアルタイム数を取得== | ||
| + | リアルタイムなコンテンツを取得することはできないみたい(2015/6時点) | ||
try { | try { | ||
$optParams = array( | $optParams = array( | ||
2015年6月12日 (金) 16:55時点における版
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']);
リアルタイム数を取得
リアルタイムなコンテンツを取得することはできないみたい(2015/6時点)
try {
$optParams = array(
'dimensions' => 'rt:medium');
$results = $analytics->data_realtime->get(
"ga:".PROFILE_ID,
'rt:activeUsers',
$optParams
);
$totals = $results->getTotalsForAllResults();
print nl2br(print_r($totals,1)); // 下記*1に示す
if (count($results->getRows()) > 0) {
foreach ($results->getRows() as $row) {
print nl2br(print_r($row,1)); // 下記*2に示す
}
}
} catch (apiServiceException $e) {
echo $e->getMessage();
}
*1
Array
(
[rt:activeUsers] => 721
)
*2
Array
(
[0] => DIRECT
[1] => 383
)
Array
(
[0] => ORGANIC
[1] => 327
)
Array
(
[0] => REFERRAL
[1] => 1
)
Array
(
[0] => SOCIAL
[1] => 10
)
参考
http://www.karakaram.com/google-analytics-api-batch
http://syncer.jp/google-analytics-api-tutorial
公式リアルタイムページ https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get?hl=ja
