简体   繁体   English

Google Analytics API(PHP)从第二个属性中提取数据

[英]Google Analytics API (PHP) pull data from second property

For a particular website in my Google Analytics account, two properties are registered for the same website. 对于我的Google Analytics(分析)帐户中的特定网站,该网站注册了两个属性。 Don't know who set it up like this first, but for now the first one has data from, say, 2010 to 2012, and the second has 2013 onward. 不知道是谁第一个这样设置的,但目前第一个具有从2010年到2012年的数据,第二个具有2013年以后的数据。 I want to access the second property. 我想访问第二个属性。 Here's what the reporting page looks like (names smudged out): 这是报告页面的样子(名称被弄脏):

在此处输入图片说明

By following the official tutorial for PHP, I'm able to access the first account and display its total sessions. 通过遵循PHP的官方教程,我可以访问第一个帐户并显示其总会话。 But I'm not able to access the second account. 但是我无法访问第二个帐户。 I thought I'd change the following function: 我以为我会更改以下功能:

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.');
    }
}

The $index = 0; $index = 0; thing you see is what I did, thinking that just by changing $index to 1 or something, I'll be able to access the next property, but it throws me an error saying Call to a member function getId() on a non-object on the code $firstAccountId = $items[$index]->getId(); 您所看到的是我所做的事情,以为只要将$ index更改为1或类似的值,我就可以访问下一个属性,但是这引发了我一个错误Call to a member function getId() on a non-object代码上的Call to a member function getId() on a non-object $firstAccountId = $items[$index]->getId();

Any help will be appreciated. 任何帮助将不胜感激。

The problem you are having is probably related to the fact that you are using an old tutorial. 您遇到的问题可能与您使用的是旧教程有关。 Which uses Oauth2 and the old PHP client lib. 它使用Oauth2和旧的PHP客户端库。 Because you are only trying to access your own data I recommend you go with a service account. 因为您仅尝试访问自己的数据,所以我建议您使用服务帐户。

The current php client lib can be found on github: Google-api-php-client 当前的php客户端库可以在github上找到: Google-api-php-client

Below is the code from my tutorial on using a service account with php to access Google Analytics Data. 以下是我的教程中有关将服务帐户与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>     

Make sure that you give the service account email address access at the Account level in Google Analytics. 确保您在Google Analytics(分析)的Account级别授予service account email address访问权限。

Code ripped from the tutorial: Google Service account PHP 教程中摘录的代码: Google服务帐户PHP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM