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

Google Analytics API(PHP)从第二个属性提取数据,php,google-analytics-api,Php,Google Analytics Api,对于我的Google Analytics帐户中的特定网站,同一个网站注册了两个属性。不知道是谁先建立的,但现在第一个有2010年到2012年的数据,第二个是2013年以后的数据。我想访问第二个属性。以下是报告页面的外观(名称被涂掉): 通过遵循PHP的官方教程,我能够访问第一个帐户并显示其总会话。但我无法访问第二个帐户。我想我应该更改以下函数: function getFirstprofileId(&$analytics) { $index = 0; $account

对于我的Google Analytics帐户中的特定网站,同一个网站注册了两个属性。不知道是谁先建立的,但现在第一个有2010年到2012年的数据,第二个是2013年以后的数据。我想访问第二个属性。以下是报告页面的外观(名称被涂掉):

通过遵循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.');
    }
}
函数getFirstprofileId(&$analytics){
$index=0;
$accounts=$analytics->management_accounts->listManagementAccounts();
回声“;
打印(账户);
回声“;
如果(计数($accounts->getItems())>0){
$items=$accounts->getItems();
$firstAccountId=$items[$index]->getId();
$webproperties=$analytics->management\u webproperties
->listManagementWebproperties($firstAccountId);
如果(计数($webproperties->getItems())>0){
$items=$webproperties->getItems();
$firstWebpropertyId=$items[$index]->getId();
$profiles=$analytics->management\u profiles
->listManagementProfiles($firstAccountId,$firstWebpropertyId);
如果(计数($profiles->getItems())>0){
$items=$profiles->getItems();
返回$items[$index]->getId();
}否则{
抛出新异常(“未找到此用户的视图(配置文件)”;
}
}否则{
抛出新异常(“未找到此用户的webproperties”);
}
}否则{
抛出新异常(“未找到此用户的帐户”);
}
}
$index=0您看到的就是我所做的,我认为只要将$index更改为1或其他什么,我就可以访问下一个属性,但它会引发一个错误,即
调用非对象上的成员函数getId()
对代码
$firstAccountId=$items[$index]->getId()


任何帮助都将不胜感激。

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

当前php客户端库可以在github上找到:

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

session_start();
需要一次“Google/Client.php”;
需要_once“Google/Service/Analytics.php”;
/************************************************   
在设置中找到以下3个值
对于您在Google上创建的应用程序
开发人员控制台。开发人员控制台。
密钥文件应放置在某个位置
这是无法从web访问的。外
网络根。网络根。
为了访问您的GA帐户,您必须
将电子邮件地址作为用户添加到
GA管理员中的帐户级别。
************************************************/
$client_id='1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address='1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com';     
$key_file_location='62975151313db09cd21a941399389f33e5abd633c9 privatekey.p12';
$client=新的Google_客户端();
$client->setApplicationName(“客户机库示例”);
$key=file\u get\u contents($key\u file\u location);
//用逗号分隔其他作用域
$scopes=”https://www.googleapis.com/auth/analytics.readonly";  
$cred=新的谷歌认证断言属性(
$Email_地址,
数组($scopes),
$key
);     
$client->setAssertionCredentials($cred);
如果($client->getAuth()->isAccessTokenExpired()){
$client->getAuth()->refreshTokenWithAssertion($cred);
}       
$service=新的谷歌服务分析($client);
$accounts=$service->management_accountSummaries->listManagementAccountSummaries();
//计算开始日期
$date=新日期时间(日期(“Y-m-d”);
$date->sub(新的日期间隔('P10D'));
//添加维度
$params=array('dimensions'=>'ga:userType');
//请求数据
$data=$service->data_ga->get(“ga:78110423”,$date->format('Y-m-d')、date(“Y-m-d”)、“ga:users,ga:sessions”、$params);
?>     
返回的行数
确保您在Google Analytics的
帐户
级别提供了
服务帐户电子邮件地址
访问权限


从教程中撕下的代码:

您到底在遵循什么教程?您不使用帐户摘要报告而不进行所有这些调用的原因是什么?@DaImTo This:。不知道怎么做。你能,请,请给我指一个有用的资源吗?甚至一本书也行。我也这么想。该教程使用了旧的客户机库,我要求它重复更新。谷歌没有更新,所以我有。注意:我希望避免OAuth,直接从脚本中提取数据。你有什么推荐的教程吗?@DaImTo看来这就是我错的地方。我需要添加在控制台中生成的电子邮件ID,而我认为将我的官方电子邮件地址添加到帐户就可以了。我会试试看!正如您所说的,我得到了以下例外:
(403)用户没有足够的权限访问此配置文件。该项目是由管理员帐户创建的,服务帐户是由具有读取/分析权限的管理员帐户创建的,同意屏幕已正确设置,但这是错误的。这是我的密码:很抱歉一再打扰你(ga:78110423“Doh!我觉得自己像个白痴。它现在起作用了!真是太感谢你了!!!!):D:D:D:D:Dnp添加屏幕截图提高了t
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>