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

前端之家收集整理的这篇文章主要介绍了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.

原文链接:https://www.f2er.com/php/134111.html

猜你在找的PHP相关文章