Created
December 15, 2019 12:52
-
-
Save itchief/e3018558ab7533a511a3baae42e4cf6b to your computer and use it in GitHub Desktop.
How to get pageviews of resource from Google Analytics Reporting API v4 and save them to file in JSON format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Загрузим PHP клиентскую библиотеку для Google API. | |
require_once __DIR__ . '/vendor/autoload.php'; | |
$analytics = initializeAnalytics(); | |
$response = getReport($analytics); | |
//printResults($response); | |
printResultInFile($response); | |
/** | |
* Инициализация сервисного объекта Analytics Reporting API V4. | |
* | |
* @return авторизованный сервисный объект Analytics Reporting API V4. | |
*/ | |
function initializeAnalytics() | |
{ | |
// здесь нужно указать имя JSON-файла, содержащего сгенерированный ключ | |
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json'; | |
// Создание и конфигурирование нового клиентского объекта. | |
$client = new Google_Client(); | |
$client->setApplicationName("Views page"); | |
$client->setAuthConfig($KEY_FILE_LOCATION); | |
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); | |
$analytics = new Google_Service_AnalyticsReporting($client); | |
return $analytics; | |
} | |
/** | |
* запрос через Analytics Reporting API V4. | |
* | |
* @param авторизованный сервисный объект Analytics Reporting API V4. | |
* @return ответ Analytics Reporting API V4. | |
*/ | |
function getReport($analytics) { | |
// здесь нужно указать значение своего VIEW_ID | |
$VIEW_ID = "<REPLACE_WITH_VIEW_ID>"; | |
// диапазон дат | |
$dateRange = new Google_Service_AnalyticsReporting_DateRange(); | |
$dateRange->setStartDate("2014-01-01"); // старт проекта | |
$dateRange->setEndDate("today"); | |
// задание метрики, равное ga:pageviews | |
$pageviews = new Google_Service_AnalyticsReporting_Metric(); | |
$pageviews->setExpression("ga:pageviews"); | |
$pageviews->setAlias("pageviews"); | |
// создание параметра ga:pagePath | |
$pagepath = new Google_Service_AnalyticsReporting_Dimension(); | |
$pagepath->setName("ga:pagePath"); | |
// создание группы фильтров по параметру | |
$dimensionFilterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause(); | |
$dimensionFilterClause->setFilters($dimensionFilter); | |
// создадим объект ReportRequest (запрос) | |
$request = new Google_Service_AnalyticsReporting_ReportRequest(); | |
// добавим к запросу идентификатор viewId | |
$request->setViewId($VIEW_ID); | |
// количество записей | |
$request->setPageSize("50000"); | |
// добавим к запросу диапазон дат | |
$request->setDateRanges($dateRange); | |
// добавим к запросу показатели | |
$request->setMetrics(array($pageviews)); | |
// добавим к запросу параметры | |
$request->setDimensions(array($pagepath)); | |
// создадим объект GetReportsRequest | |
$body = new Google_Service_AnalyticsReporting_GetReportsRequest(); | |
$body->setReportRequests( array( $request) ); | |
return $analytics->reports->batchGet( $body ); | |
} | |
/** | |
* Парсинг и печать Analytics Reporting API V4 ответа. | |
* | |
* @param ответ Analytics Reporting API V4. | |
*/ | |
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"); | |
} | |
} | |
} | |
} | |
} | |
// возвращение ответа в формате JSON, который нужно положить в файл /assets/ga_pageviews.json | |
function printResultInFile($reports) { | |
$darray = array(); | |
$marray = array(); | |
$mkey = array(); | |
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 ($j = 0; $j < count($metricHeaders); $j++) { | |
$entry = $metricHeaders[$j]; | |
$mkey[] = $entry->getName(); | |
} | |
for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) { | |
$row = $rows[$rowIndex]; | |
$dimensions = $row->getDimensions(); | |
$metrics = $row->getMetrics(); | |
$darray[] = array_combine($dimensionHeaders, $dimensions); | |
for ($j = 0; $j < count($metrics); $j++) { | |
$values = $metrics[$j]->getValues(); | |
$marray[] = array_combine($mkey, $values); | |
} | |
} | |
} | |
$i = 0; | |
$mdarray = array(); | |
foreach($darray as $value) { | |
$mdarray[] = array_merge($value, $marray[$i]); | |
$i++; | |
} | |
$json_data = json_encode($mdarray); | |
file_put_contents($_SERVER['DOCUMENT_ROOT'].'/assets/ga_pageviews.json', $json_data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment