$dimensions , 'max-results' => 100 , // 'sort' => '-ga:yearMonth' , 'filters' => 'ga:deviceCategory==desktop,ga:deviceCategory==mobile,ga:deviceCategory==tablet' , // '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 { $html .= '
' ; // 解析 for( $i=0 , $l=count( $obj->rows ) ; $l > $i ; $i++ ) { // エイリアス $item = $obj->rows[ $i ] ; // 出力 $html .= '
' . $item[0] . '
' ; $html .= '
' . number_format( $item[1] ) . ' PV
' ; $html .= '
' . ( round( ( $item[1] / $obj->totalsForAllResults['ga:pageviews'] ) , 4 ) * 100 ) . ' %
' ; } $html .= '
' ; } // 取得したデータ $html .= '

取得したデータ(JSON)

' ; $html .= '' ; ?> Google Analytics APIでデバイス別のページニュー数と割合を取得するサンプルデモ

配布元: Syncer