Search code examples
google-analyticsgoogle-analytics-apigoogle-php-sdk

Filter by country


I want get all regions for a country from my Google Analytics account. I wrote the below code to get all regions:

$metrics = 'ga:visits';
$dimensions = 'ga:country=$iso,ga:region,ga:regionId';

$ga = $this->getGa();
$gaResponse = $ga->data_ga->get('ga:122752178', $start, $end, $metrics, ['dimensions' => $dimensions]);
$resultset = $gaResponse->getRows();

So, how i can get all regions for a country ? For example, Argentina (AR).


Solution

  • First a suggestion: Try your query out in the query Explorer.

    Answer: Use the filters parameter.

    Filter by ga:country==Argentina.

    $metrics = 'ga:sessions';
    
    $optParams = array(
      'dimensions' => 'ga:country,ga:region,ga:regionId',
      'sort' => '-ga:sessions',
      'filters' => 'ga:country==Argentina',
      'max-results' => '25');
    
    $ga = $this->getGa();
    $gaResponse = $ga->data_ga->get(
        $ids,
        $start,
        $end,
        $metrics,
        $optParams);
    $resultset = $gaResponse->getRows();
    

    This will get you a list of all the regions from which you had sessions, not an extensive list of regions within a country.

    Also ga:visists is deprecated, you should use ga:sessions, see the Core Reporting API Docs and Dimensions and Metrics Reference.