目前我正在尝试使用 Google Analytics Data API v1 从 GA4 获取 json 数据。但是,返回的响应不是纯 json 数据,相反,如果我只是使用 PHP 打印它,它会给我 {}。但是,使用预定义的方法,我们可以获得该值。请问,有没有办法得到纯json数据?
<?php
putenv('GOOGLE_APPLICATION_CREDENTIALS=xxx.json');
require_once 'vendorautoload.php';
use GoogleAnalyticsDataV1betaBetaAnalyticsDataClient;
use GoogleAnalyticsDataV1betaDateRange;
use GoogleAnalyticsDataV1betaDimension;
use GoogleAnalyticsDataV1betaMetric;
use GoogleCloudBigQueryConnectionRest;
$property_id = 'xxx'; // GA4 property ID
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
$client = new BetaAnalyticsDataClient();
// Make an API call.
$response = $client->runReport([
'property' => 'properties/' . $property_id,
'dateRanges' => [
new DateRange([
'start_date' => '2022-06-30',
'end_date' => 'today',
]),
],
'dimensions' => [
new Dimension(
[
'name' => 'city',
]
),
],
'metrics' => [
new Metric(
[
'name' => 'activeUsers',
]
)
]
]);
print 'Report result: ' . PHP_EOL;
printVisitorsLocationInNumber($response);
function printVisitorsLocationInNumber($resp) {
foreach ($resp->getRows() as $row) {
echo
$row->getDimensionValues()[0]->getValue() . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL . '</br>';;
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
$response是\Google\Analytics\Data\V1beta\RunReportResponse的实例,它扩展自\Google\Protobuf\Internal\Message。因此,您可以使用相同的serializeToJsonString()方法。