Google AnalyticsAPI(PHP)从第二个媒体资源中提取数据

时间:2014-11-07 08:44:53

标签: php google-analytics-api

对于我的Google Analytics帐户中的特定网站,会为同一网站注册两个属性。不知道是谁首先设置了它,但是现在第一个有来自2010年到2012年的数据,第二个有2013年以后的数据。我想访问第二个属性。这是报告页面的样子(名字被抹掉):

enter image description here

通过遵循PHP的官方教程,我能够访问第一个帐户并显示其总会话数。但是我无法访问第二个帐户。我以为我改变了以下功能:

function getFirstprofileId(&$analytics) {

    $index = 0;
    $accounts = $analytics->management_accounts->listManagementAccounts();

    echo "<pre>";
    print_r($accounts);
    echo "</pre>";

    if (count($accounts->getItems()) > 0) {
        $items = $accounts->getItems();
        $firstAccountId = $items[$index]->getId();

        $webproperties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

        if (count($webproperties->getItems()) > 0) {
            $items = $webproperties->getItems();
            $firstWebpropertyId = $items[$index]->getId();

            $profiles = $analytics->management_profiles
            ->listManagementProfiles($firstAccountId, $firstWebpropertyId);

            if (count($profiles->getItems()) > 0) {
                $items = $profiles->getItems();
                return $items[$index]->getId();

            } else {
                throw new Exception('No views (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.');
    }
}

你看到$index = 0;的东西就是我所做的,认为只要将$ index改为1或者其他东西,我就能够访问下一个属性,但它会让我错误地说{代码Call to a member function getId() on a non-object

上的{1}}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您遇到的问题可能与您使用旧教程有关。其中使用Oauth2和旧的PHP客户端库。因为您只是尝试访问自己的数据,所以我建议您使用服务帐户。

当前的php客户端库可以在github上找到:Google-api-php-client

以下是我使用php服务帐户访问Google Analytics数据的教程中的代码。

session_start();        
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';        
/************************************************   
 The following 3 values an befound in the setting   
 for the application you created on Google      
 Developers console.         Developers console.
 The Key file should be placed in a location     
 that is not accessable from the web. outside of 
 web root.       web root.

 In order to access your GA account you must    
 Add the Email address as a user at the     
 ACCOUNT Level in the GA admin.         
 ************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com';     
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';     
$client = new Google_Client();      
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);    
// seproate additional scopes with a comma   
$scopes ="https://www.googleapis.com/auth/analytics.readonly";  
$cred = new Google_Auth_AssertionCredentials(    
 $Email_address,         
 array($scopes),        
 $key        
 );     
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {        
 $client->getAuth()->refreshTokenWithAssertion($cred);      
}       
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
//calulating start date  
$date = new DateTime(date("Y-m-d"));     
$date->sub(new DateInterval('P10D'));    
//Adding Dimensions
$params = array('dimensions' => 'ga:userType'); 
// requesting the data  
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );  
?><html>     
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>    
<table>  
<tr>     
<?php    
//Printing column headers
foreach($data->getColumnHeaders() as $header){
 print "<td>".$header['name']."</td>";      
}       
?>      
</tr>       
<?php       
//printing each row.
foreach ($data->getRows() as $row) {        
 print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";      
}    
//printing the total number of rows
?>      
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>     
</table>     
</html>     

确保您在Google Analytics中service account email address级别提供Account访问权限。

从教程Google Service account PHP

中删除了代码