从脚本中获取访问者数量

Bas*_*asj 7 php analytics google-analytics google-analytics-api

我知道如何使用Data Studio或Javascript中的Google Apps脚本访问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);
Run Code Online (Sandbox Code Playgroud)

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

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

输出:[19873,17873,13999,21032,...,16321](即www.example.com最后30天中每一天的访问次数,作为整数列表或JSON)

Jos*_*ata 1

我使用这个包:

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
}
Run Code Online (Sandbox Code Playgroud)

另外,这里还有关于如何使用 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 您不能直接使用用户名和密码。