php – 从脚本中获取访问者数量

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 从脚本中获取访问者数量脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
知道如何使用Data Studiowith Google Apps script在Javascript中访问Google Analytics数据:
VAR account = Analytics.Management.Accounts.list().ITems[0];
var webPRoPErties = Analytics.Management.Webproperties.list(account.id);
...
var report = Analytics.Data.Ga.get(tableid,startDate,endDate,metric,options);

但在PHP中,如何从Google Analytics帐户/属性/视图中检索特定网站或特定网页的访问者数量?即:

输入:分析帐户登录/密码/网站代码’UA-XXXXX-Y’

输出:[19873,17873,13999,21032,…,16321](即www.example.COM上30个最后几天的访问次数,作为整数列表或JSON)

我用这个包:

https://github.com/google/google-api-php-client

您可以使用它来访问PHP中的所有Google Api,当然包括Google Analytics

以下是如何使用它的示例:

// create client object and set app name
$client = new GOOGLE_Client();
$client->setApplicationName('Your app name'); // name of your app

// set assertion credentials
$client->setAssertionCredentials(
    new Google_AssertionCredentials(
        'your_analytics_email@gmail.com',// email you added to GA
        [
            'https://www.googleapis.com/auth/analytics.readonly'),file_get_contents('/your/key/file.p12') // keyfile you downloaded
        ]
    )
);

// other settings
$client->setClientId('your-client-id'); // From API console
$client->setAccessType('offline_access'); // this may be unnecessary?

// create service and get data
$service = new Google_AnalyticsService($client);

$from_date = date("Y-m-d",strtotime("-30 days")); // A month
$to_date = date("Y-m-d");

$response = $service->data_ga->get(
    "ga:profile_id",// profile id
    "$from_date",// start date
    "$to_date",// end date
    "ga:uniquePageviews",[   
        'dimensions' => 'ga:pagePath',// Dimensions you want to include,pagePath in this example
        'sort' => '-ga:uniquePageviews',// Sort order,order by unique page views from high to low in this case
        'filters' => 'ga:pagePath=~\/articles\/[a-zA-Z0-9\-]+',// example url filter
        'max-results' => '50' // Max results
    ]
);
foreach ($response["rows"] as $row) {
    // ...do whatever you want with the results
}

另外,以下是有关如何使用Google Api的指南:

https://developers.google.com/api-client-library/php/start/get_started

编辑:您需要创建凭据才能访问Analytics API.您可以在此处执行:https://console.cloud.google.com/flows/enableapi?apiid=analyticsreporting.googleapis.com&credential=client_key.您需要先注册项目,然后创建凭据.有三个选项:API密钥,OAuth客户端ID和服务帐户密钥.我不想使用OAuth,因此我使用了服务帐户密钥.您可以尝试使用API​​密钥,在这种情况下,请替换$client-> setAssertionCredentials(…)调用$client-> setDeveloperKey(your_api_key).您不能直接使用用户名和密码AFAIK.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 从脚本中获取访问者数量全部内容,希望文章能够帮你解决php – 从脚本中获取访问者数量所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。