[精讚] [會員登入]
2257

設定Google analytics API #2 -- PHP的程式安裝和撰寫

讓你的網站能夠存取你的Google analytics上面的資料

分享此文連結 //n.sfs.tw/11587

分享連結 設定Google analytics API #2 -- PHP的程式安裝和撰寫@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-25 10:24:22 最後編修
2017-08-10 02:43:49 By 張○○
 

自動目錄

此文分成三個部分

設定Google analytics API #1 -- Google網站上的設定

設定Google analytics API #2 -- PHP的程式安裝和撰寫

設定Google analytics API #3 -- 查詢範例

三、安裝Google的Library(PHP)

google的文件[1]說明要用composer安裝他的library,如果你沒有composer,可以參考 [Centos7] 安裝php套件管理程式Composer+ Codeignioter3 這裡來安裝,基本上安裝google library沒有任何問題。

$ composer require google/apiclient:^2.0

安裝完畢後你會出現一個google的library目錄

google/
├── apiclient
├── apiclient-services
└── auth

四、叫用 google apiclient

只要依composer 的方式載入即可,因為我把google的範例放到CI3的類別中,所以寫法稍有改變,基本上大部分依[1]所寫的範例作測試。

叫用

public function doAnalytics(){
    include  APPPATH. "third_party/autoload.php";  //載入composer的 autoload
    $analytics = $this->initializeAnalytics();  //載入帳號資料
    $profileid = $this->getProfileIdByName($analytics,'新精讚');
    $results = $this->getResults($analytics, $profileid); //由profile id取回資料
    $this->printResults($results);
}

初始化載入帳號資料

private function initializeAnalytics()
{
    $KEY_FILE_LOCATION = APPPATH. "config/note_ana.json";
    $client = new Google_Client();
    $client->setApplicationName("Hello Analytics Reporting");
    $client->setAuthConfig($KEY_FILE_LOCATION);
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
    $analytics = new Google_Service_Analytics($client);
    return $analytics;
}

第3行 note_ana.json 就是前面二步驟下載的json檔,請確認路徑正確

由property name取回profile id

其中的name就是property name,也就是你在google analytics上面設定的名稱,例如:

private function getProfileIdByName($analytics,$name) {
    $accounts = $analytics->management_accounts->listManagementAccounts();
    if (count($accounts->getItems()) <= 0) {
      throw new Exception('No accounts found for this user.');
    }
    $accitems = $accounts->getItems();
    $firstAccountId = $accitems[0]->getId();
    $properties = $analytics->management_webproperties 
->listManagementWebproperties($firstAccountId);
    $items = $properties->getItems();
    if (count($items) <= 0) throw new Exception('No properties found for this user.');
    $n=-1;
    foreach($items as $k=>$one){
      if(!strcmp($one->getName(),$name)){$n=$k; break;}
    }
    if($n==-1)throw new Exception('No profile found for this name.');
    $PropertyId = $items[$n]->getId();
    $profiles = $analytics->management_profiles 
->listManagementProfiles($firstAccountId, $PropertyId);
    if (count($profiles->getItems()) <= 0) {
      throw new Exception('No views (profiles) found for this user.');
    }
    $profileobj= $profiles->getItems();
    return $profileobj[0]->getId();
}

1-7行 取回account id,有多筆取回第1筆
8-10行 取回properties的項目,一個帳號可能有多個google analytics的properties
12-17行 判斷取回的properties名稱是否符合,優先符合優先取回 property id
18-24行 每個property可能有單個或多個profile,取回第一個profile的id

取回資料項目

private function getResults($analytics, $profileId) {
    // Calls the Core Reporting API and queries for the number of sessions
    // for the last seven days.
    return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:sessions');
}

其中的參數可參考[3][4]:
  第5行:VIEW_ID: ga:132128590
  第6行:起始日期
  第7行:結束日期
  第8行:matrics,查詢session

印出結果

此部分和Google文件提供的一樣,請自行發揮了

private function printResults($results) {
    if (count($results->getRows()) > 0) {
      $profileName = $results->getProfileInfo()->getProfileName();
      $rows = $results->getRows();
      $sessions = $rows[0][0];
      print "First view (profile) found: $profileName\n";
      print "Total sessions: $sessions\n";
    } else {
      print "No results found.\n";
    }
}

執行結果

First view (profile) found: 所有網站資料
Total sessions: 5678

下一篇 設定Google analytics API #3 -- 查詢範例

參考資料

[1] https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-php

[2] 所有API的文件請參考 https://developers.google.com/analytics/devguides/config/mgmt/v3/

[3] https://developers.google.com/analytics/devguides/reporting/core/v3/reference

[4] https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide

[5] Hierarchy of accounts, users, properties, and views https://support.google.com/analytics/answer/1009618

END

你可能感興趣的文章

PHP 移除陣列中的元素 要移除陣列中的其中一項元素

[PHP] 取得檔名和路徑:basename, dirname 由絕對路徑取的路徑及檔名的方法

[PHP] 使用browscap檢查瀏覽器版本 使用PHP內建函數browscap檢查瀏覽器版本

[Codeingitor4] 使用recaptcha v3前後端認證 為了防止機器人說惡意攻擊,我們引入了 recaptcha,此篇結合 php 框架codeignitor4作前後端認證。

[PHP] 解析二進位圖片 使用php來解析png圖片,把資料寫在16進位格式

[phpmyadmin] 錯誤:您應升級到 MySQL 5.5.0 或更新版本 使用phpmyadmin4出現錯誤:您應升級到 MySQL 5.5.0 或更新版本的解決方式

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

SELinux 常用指令和檔案 在Redhat系列中,Centos5以後加入了selinux,他並沒有這麼可怕,不必每次看到Selinux ,就想把他

[Freebsd] 使用 ADSL 撥接上網 Freebsd上要使用 ADSL 撥接上網,該如何設定?

[Windows7] 移除IE10及移除IE11 Windows7 不得已的情況要移除IE11或IE10怎麼做?

看懂DSUB DVI HDMI USB等各式影音接頭 看懂DSUB DVI HDMI等各式影音接頭

TFTP Server 安裝及使用 讓設備的網路設定檔或是韌體經由TFTP拷備出來,操作的方法