PHP Google AnalyticsAPI – 简单示例

前端之家收集整理的这篇文章主要介绍了PHP Google AnalyticsAPI – 简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试设置一个使用此库的Google Analytics的基本示例: https://github.com/google/google-api-php-client

对于初学者我有:

<?PHP

require_once 'Google/Client.PHP';
require_once 'Google/Service/Analytics.PHP';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("MY_SECRET_API"); //security measures
$service = new Google_Service_Analytics($client);

$results = $service->data_ga;

echo '<pre>';
print_r($results);
echo '</pre>';

问:如何从此查询获取Google Analytics中的数据?

/*
  https://www.googleapis.com/analytics/v3/data/
  ga?ids=ga%123456
  &dimensions=ga%3Acampaign
  &metrics=ga%3Atransactions
  &start-date=2013-12-25
  &end-date=2014-01-08
  &max-results=50
 */
$client->setDeveloperKey("MY_SECRET_API");

首先,据我所知,这不适用于身份验证,您需要使用OAuth2身份验证.有两种方法可以执行此操作,使用客户端ID进行Web应用程序或使用服务帐户. Authorization api

完成后,你可以这样打个电话.
(我在这里使用服务帐户)

首先验证:

$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,array('https://www.googleapis.com/auth/analytics.readonly'),$key
);
$client->setAssertionCredentials($cred);

打个电话:

$ids = 'ga:123456'; //your id
$startDate = '2013-12-25';
$endDate = '2014-01-08';
$metrics = 'ga:transactions';

$optParams = array(
    'dimensions' => 'ga:campaign','max-results' => '50'
);

$results = $service->data_ga->get($ids,$startDate,$endDate,$metrics,$optParams);

//Dump results
echo "<h3>Results Of Call:</h3>";

echo "dump of results";
var_dump($results);

echo "results['totalsForAllResults']";
var_dump($results['totalsForAllResults']);

echo "results['rows']";
foreach ($results['rows'] as $item) {
    var_dump($item);
}

猜你在找的PHP相关文章