Heim  >  Fragen und Antworten  >  Hauptteil

Google Analytics Data API v1: Führen Sie runReport aus und rufen Sie nur JSON-Daten ab

Derzeit versuche ich, JSON-Daten von GA4 mithilfe der Google Analytics Data API v1 abzurufen. Allerdings handelt es sich bei der zurückgegebenen Antwort nicht um reine JSON-Daten. Wenn ich sie einfach mit PHP ausdrucke, erhalte ich stattdessen {}. Mit vordefinierten Methoden können wir jedoch den Wert ermitteln. Gibt es eine Möglichkeit, reine JSON-Daten zu erhalten?

<?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粉356361722P粉356361722285 Tage vor330

Antworte allen(1)Ich werde antworten

  • P粉726133917

    P粉7261339172023-12-14 14:35:28

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

    $response\Google\Analytics\Data\V1beta\RunReportResponse 的实例,它扩展自 \Google\Protobuf\Internal\Message< /代码>。因此,您可以使用相同的 serializeToJsonString() 方法。

    Antwort
    0
  • StornierenAntwort