这个问题更多地与 PHP 的机制与 Google 的核心报告 API 的复杂性有关
我的目标是修改下面的代码(取自谷歌的 HelloAnalyticsApi.php),以便它循环并“打印”我所有各自谷歌分析帐户的配置文件 ID列表。
目前,下面的代码通过并获取它看到的第一个帐户的第一个配置文件 ID。它首先获取帐户 ID,然后是该帐户 ID 的网络资源,最后是帐户的配置文件 ID。这是在getFirstprofileId(&$analytics)函数中完成的。照原样,代码工作正常。
就我而言,我必须跳过第一个(数组中的位置 0),因为虽然它是一个被列出的帐户,但它没有任何网络属性。因此,我必须从 1 而不是 0 开始计数。
(我将跳过凭据/登录并获取工作逻辑)
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new apiAnalyticsService($client);
runMainDemo($analytics);
}
function runMainDemo(&$analytics) {
try {
// Step 2. Get the user's first profile ID.
$profileId = getFirstProfileId($analytics);
if (isset($profileId)) {
// Step 3. Query the Core Reporting API.
$results = getResults($analytics, $profileId);
// Step 4. Output the results.
printResults($results);
}
} catch (apiServiceException $e) {
// Error from the API.
print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
} catch (Exception $e) {
print 'There wan a general error : ' . $e->getMessage();
}
}
function getFirstprofileId(&$analytics) {
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[1]->getId();
//item 0 is an account that gets listed but doesn't have any webproperties.
//This account doesn't show in our analytics
$webproperties = $analytics->management_webproperties->listManagementWebproperties($firstAccountId);
if (count($webproperties->getItems()) > 0) {
$items = $webproperties->getItems();
$firstWebpropertyId = $items[0]->getId();
$profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstWebpropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
return $items[0]->getId();
} else {
throw new Exception('No profiles found for this user.');
}
} else {
throw new Exception('No webproperties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults(&$analytics, $profileId) {
return $analytics->data_ga->get(
'ga:' . $profileId,
'2010-03-03',
'2011-03-03',
'ga:visits');
}
function printResults(&$results) {
if (count($results->getRows()) > 0) {
$profileName = $results->getProfileInfo()->getProfileName();
$profileId = $results->getProfileInfo()->getProfileId();
$rows = $results->getRows();
$visits = $rows[0][0];
print "<p>First profile found: $profileName</p>";
print "<p>First profileId found (not account id): $profileId</p>";
print "<p>Total visits: $visits</p>";
} else {
print '<p>No results found.</p>';
}
}
?>