google analytics api query a specific url

2020-02-23 09:01发布

I am accessing the Google analytics API with PHP which works on my end but I'd love to filter the results a bit further. Right now I am using:

$OBJresult = $analytics -> data_ga -> get(
    'ga:' . $profilID,
    '2012-01-01',
    date( "Y-m-d" ),
    'ga:visits',
    array(
        'dimensions' => 'ga:pagePath',
        'metrics' => 'ga:pageviews',
        'sort' => '-ga:pageviews',
        'max-results' => '25'
    )
);

Currently this returns a set of 25 pages sorted by its hits. I would love to restrict the results to a specific path within the server. So e.g. only query domain.com/news and only see what the most hit news pages are. I can filter with PHP but rather have the query as specific as possible.

Thanks for the help

3条回答
我只想做你的唯一
2楼-- · 2020-02-23 09:31

Reporting V4 example that may be useful. Thank god for these queries, their objects and poor documentation can cause severe ass cancer..

function segmentRequest(&$analyticsreporting) {

$query = [
        "viewId" => "XXXXXXX",
        "dateRanges" => [
            "startDate" => "2018-02-01",
            "endDate" => "2018-02-15"
        ],
        "metrics" => [
            "expression" => "ga:pageviews"
        ],
        "dimensions" => [
            "name" => "ga:pagepath"
        ],
        "dimensionFilterClauses" => [
            'filters' => [
                "dimension_name" => "ga:pagepath",
                "operator" => "EXACT",
                "expressions" => "/en/some_cool_page.php"
            ]
        ]
    ];

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $query) );
  $response = $analyticsreporting->reports->batchGet( $body );

  printResults($response->getReports());
}
查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-23 09:44

Use the filters option.

$OBJresult = $analytics->data_ga->get(
    'ga:' . $profilID,
    '2012-01-01',
    date("Y-m-d"),
    'ga:visits',
    array(
        'filters' => 'ga:pagePath==/news',
        'dimensions' => 'ga:pagePath',
        'metrics' => 'ga:pageviews',
        'sort' => '-ga:pageviews',
        'max-results' => '25'
    )
);

See here for the list of page tracking dimensions you can filter on.

查看更多
姐就是有狂的资本
4楼-- · 2020-02-23 09:51

You need to use the filters string to say "if path includes /news" which can be done as follows:

$OBJresult=$analytics->data_ga->get(
    'ga:'.$profilID,
    '2012-01-01',
    date("Y-m-d"),
    'ga:visits',
    array(
        'filters' => 'ga:pagePath=@/news',
        'dimensions' => 'ga:pagePath',
        'metrics' => 'ga:pageviews',
        'sort' => '-ga:pageviews',
        'max-results' => '25'));

The answer supplied by Barmar will only find an exact match for the /news page.

查看更多
登录 后发表回答