Search code examples
phpgoogle-analytics-apigoogle-analytics-4

Google Analytics Data API v1 runReport and only return JSON


currently I am trying to get the json data from GA4 using Google Analytics Data API v1. However, the response given back is not a pure json data, instead if I just print it using PHP, it gives me {}. However, using the predefined method, we can get the value. May I know, is there anyway I can get a pure json data?

<?php
putenv('GOOGLE_APPLICATION_CREDENTIALS=xxx.json');

require_once 'vendor\autoload.php';

use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Cloud\BigQuery\Connection\Rest;

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

Solution

  • echo $response->serializeToJsonString(); // Prints JSON string
    

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