該網站網頁必須有嵌入Google Analytics的追蹤程式碼, 透過該追蹤程式碼, 該網頁被瀏覽的資訊將會被送至Google Analytics中. (https://analytics.google.com/analytics/web/)
參考https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php 啟動API並下載一個 json 格式的金鑰檔案.
若不曾建立過Analytics Reporting API須建立一個新的專案,並建立服務帳戶.
使用 composer安裝Google APIs Client Library for PHP
composer require google/apiclient:^2.0
建立一個 HelloAnalytics.php.
<?php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);
/**
* Initializes an Analytics Reporting API V4 service object.
*
* @return An authorized Analytics Reporting API V4 service object.
*/
function initializeAnalytics()
{
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
// Create and configure a new client object.
$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_AnalyticsReporting($client);
return $analytics;
}
/**
* Queries the Analytics Reporting API V4.
*
* @param service An authorized Analytics Reporting API V4 service object.
* @return The Analytics Reporting API V4 response.
*/
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "<REPLACE_WITH_VIEW_ID>";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
/**
* Parses and prints the Analytics Reporting API V4 response.
*
* @param An Analytics Reporting API V4 response.
*/
function printResults($reports) {
for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
$report = $reports[ $reportIndex ];
$header = $report->getColumnHeader();
$dimensionHeaders = $header->getDimensions();
$metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
$rows = $report->getData()->getRows();
for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[ $rowIndex ];
$dimensions = $row->getDimensions();
$metrics = $row->getMetrics();
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
}
for ($j = 0; $j < count($metrics); $j++) {
$values = $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry = $metricHeaders[$k];
print($entry->getName() . ": " . $values[$k] . "\n");
}
}
}
}
}
找到 $KEY_FILE_LOCATION=__DIR__.’/service-account-credentials.json’;這行,將 /service-account-credentials.json 改成下載的金鑰檔案名稱.
找到 $VIEW_ID = “<REPLACE_WITH_VIEW_ID>”; 將 <REPLACE_WITH_VIEW_ID> 填入專案的VIEW_ID,雙引號保留.
註: 到https://analytics.google.com找到VIEW_ID
參考範例 https://developers.google.com/analytics/devguides/reporting/core/v4/samples
參考參數 https://developers.google.com/analytics/devguides/reporting/core/dimsmets
一些參數範例
建立資料範圍
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2019-01-01");
$dateRange->setEndDate("today");
建立以頁面被瀏覽次數
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:pageviews");
$sessions->setAlias("pageViews");
抓取頁面標題及連結資料
//Create the Dimensions object.
$pagePath = new Google_Service_AnalyticsReporting_Dimension();
$pagePath->setName("ga:pagePath");
$pageTitle = new Google_Service_AnalyticsReporting_Dimension();
$pageTitle->setName("ga:pageTitle");
設定以pageViews的value為主排序從大到小
// Create the Ordering.
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setFieldName("ga:pageViews");
$ordering->setOrderType("VALUE");
$ordering->setSortOrder("DESCENDING");
向Google Request資料
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
$request->setDimensions(array($pageTitle,$pagePath));
$request->setOrderBys($ordering); // note this one!
產生報表資料
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
將資料傾印出來
function printResults(&$reports) {
for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
$report = $reports[ $reportIndex ];
$header = $report->getColumnHeader();
$dimensionHeaders = $header->getDimensions();
$metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
$rows = $report->getData()->getRows();
for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[ $rowIndex ];
$dimensions = $row->getDimensions();
$metrics = $row->getMetrics();
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "<br>\n");
}
for ($j = 0; $j < count($metrics); $j++) {
$values = $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry = $metricHeaders[$k];
print($entry->getName() . ": " . $values[$k] . "<br>\n");
}
}
}
}
}
只抓五筆資料範例
function getResults(&$reports) {
echo "資料抓取範圍:2019-01-01 至 今日<br><br>";
for ($reportIndex = 0; $reportIndex < count($reports); $reportIndex++) {
$report = $reports[ $reportIndex ];
$rows = $report->getData()->getRows();
for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[ $rowIndex ];
// 選擇網址連結帶有sid參數
if (stripos($row["dimensions"][1], 'sid')) {
// 排除網址帶有mid參數
if (!stripos($row["dimensions"][1], 'mid')) {
$pageTitle[] = $row["dimensions"][0]; //pageTitle
$pagePath[] = $row["dimensions"][1]; //pagePath
$pageViews[] = (INT)$row["metrics"][0]['values'][0]; //pageViews
}
}
}
//印出前五筆資料
for($i=0;$i<5;$i++){
echo "第".($i+1)."名 瀏覽次數".$pageViews[$i]."次<br>";
echo "第".($i+1)."名 標題".$pageTitle[$i]."<br>";
echo "第".($i+1)."名 連結".$pagePath[$i]."<br>";
echo "<br>";
}
}
echo "<br>最熱門五筆資料擷取已完成<br>";
}