この質問は、Google の Core Reporting API の複雑さよりも、PHP の仕組みに関係しています。
私の目標は、以下のコード (Google の HelloAnalyticsApi.php から取得) を変更して、ループを実行し、それぞれの Google アナリティクス アカウントのすべてからプロファイル IDのリストを "printf" することです。
現在、以下のコードが実行され、最初に表示されたアカウントの最初のプロファイル ID が取得されます。最初にアカウント ID を取得し、次にそのアカウント ID の Web プロパティを取得し、最後にアカウントのプロファイル ID を取得します。これは、getFirstprofileId(&$analytics)関数で実行されます。そのままで、コードは正常に動作します。
私の場合、最初の 1 つ (配列の位置 0) をスキップする必要があります。これは、リストされるアカウントですが、Web プロパティがないためです。したがって、0 ではなく 1 からカウントを開始する必要があります。
(資格情報/ログインをスキップして、機能するロジックを取得します)
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>';
}
}
?>