$dimensions , 'max-results' => 10 , // 'sort' => '-ga:pageviews' , // 'start-index' => 11, // 取得開始位置 ) ; // トークンのセット if( isset( $_SESSION['service_token'] ) ) { $client->setAccessToken( $_SESSION['service_token'] ) ; } // スコープのセット (読み込みオンリー) $scopes = array( 'https://www.googleapis.com/auth/analytics.readonly' ) ; // クレデンシャルの作成 $credentials = new Google_Auth_AssertionCredentials( $client_id , $scopes , $private_key ) ; // Googleクライアントのインスタンスを作成 $client = new Google_Client() ; $client->setAssertionCredentials( $credentials ) ; // トークンのリフレッシュ if( $client->getAuth()->isAccessTokenExpired() ) { $client->getAuth()->refreshTokenWithAssertion( $credentials ) ; } // セッションの設定 $_SESSION['service_token'] = $client->getAccessToken() ; // Analyticsのインスタンスを作成 $analytics = new Google_Service_Analytics( $client ) ; // データの取得 $obj = $analytics->data_ga->get( 'ga:' . $view_id , $from , $to , $metrics , $option ) ; // JSONデータに変換 $json = json_encode( $obj ) ; // HTML用 $html = '' ; // 実行結果を出力 $html .= '

実行結果

' ; $html .= '

直近1ヶ月間(' . date( 'Y/m/d' , strtotime( $from ) ) . '〜' . date( 'Y/m/d' , strtotime( $to ) ) . ')のユーザーサマリーを取得しました。値はサンプル用のダミーです。

' ; // エラー判定 if( !isset($obj->rows) ) { $html .= '

データを取得できませんでした…。

' ; } else { // 各データ $sessions = $obj->totalsForAllResults['ga:sessions'] ; // セッション $users = $obj->totalsForAllResults['ga:users'] ; // ユーザー $pageviews = $obj->totalsForAllResults['ga:pageviews'] ; // ページビュー数 $pageviewsPerSession = $obj->totalsForAllResults['ga:pageviewsPerSession'] ; // ページ/セッション $avgSessionDuration = $obj->totalsForAllResults['ga:avgSessionDuration'] ; // 平均セッション時間 $bounceRate = $obj->totalsForAllResults['ga:bounceRate'] ; // 直帰率 $percentNewSessions = $obj->totalsForAllResults['ga:percentNewSessions'] ; // 新規セッション率 // 出力 $html .= '
' ; $html .= '
セッション
' ; $html .= '
' . number_format( $sessions ) . '
' ; $html .= '
ユーザー
' ; $html .= '
' . number_format( $users ) . '
' ; $html .= '
ページビュー数
' ; $html .= '
' . number_format( $pageviews ) . '
' ; $html .= '
ページ/セッション
' ; $html .= '
' . round( $pageviewsPerSession , 2 ) . '%
' ; $html .= '
平均セッション時間
' ; $html .= '
' . sprintf( '%02d' , floor( $avgSessionDuration / 60 ) ) . ':' . sprintf( '%02d' , floor( $avgSessionDuration % 60 ) ) . '
' ; $html .= '
直帰率
' ; $html .= '
' . round( $bounceRate , 2 ) . '%
' ; $html .= '
新規セッション率
' ; $html .= '
' . round( $percentNewSessions , 2 ) . '%
' ; $html .= '
' ; } // 取得したデータ $html .= '

取得したデータ(JSON)

' ; $html .= '' ; ?> Google Analytics APIでユーザーサマリーを取得するサンプルデモ

配布元: Syncer