Google Analytics Data API v1: Execute runReport and retrieve only JSON data
P粉356361722
P粉356361722 2023-12-13 17:37:47
0
1
373

Currently I'm trying to get json data from GA4 using Google Analytics Data API v1. However, the response returned is not pure json data, instead if I just print it using PHP it gives me {}. However, using predefined methods we can get the value. Is there any way to get pure json data?

<?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>';;
  }
}


P粉356361722
P粉356361722

reply all(1)
P粉726133917
echo $response->serializeToJsonString(); // Prints JSON string

$response is an instance of \Google\Analytics\Data\V1beta\RunReportResponse, which extends from \Google\Protobuf\Internal\Message. So you can use the same serializeToJsonString() method.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!