欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Google Analytics API v3和PHP:过滤器和图表

程序员文章站 2022-06-11 12:22:04
...

In the previous parts, we talked about how to use the Google Analytics API and created a demo showing some base functionality. In this part, we’re going to expand the demo.

前面的部分中 ,我们讨论了如何使用Google Analytics(分析)API,并创建了一个展示一些基本功能的演示。 在这一部分中,我们将扩展演示。

Google Analytics API v3和PHP:过滤器和图表

新功能 (New functionality)

We’ll be adding some new functionality:

我们将添加一些新功能:

  • Date range: we can query data from a specific date range.

    日期范围:我们可以查询特定日期范围内的数据。
  • Max results: in the previous part we used 10 results for speed purposes, now we are going to take it as a user input.

    最大结果:在上一部分中,我们出于速度目的使用了10个结果,现在将其作为用户输入。
  • Filters: we can filter the result using some specific dimensions or metrics.

    过滤器:我们可以使用一些特定的维度或指标来过滤结果。
  • Order: we can order the result using the queried dimensions.

    订购:我们可以使用查询的尺寸对结果进行订购。
  • Chart type: this is not a Google Analytics functionality, but we’re going to make some prettier graphs using Highcharts.

    图表类型:这不是Google Analytics(分析)功能,但是我们将使用Highcharts制作一些更漂亮的图表。

日期范围 (Date range)

For the date range selection we’re going to use bootstrap-daterangepicker. First, we include the CSS and JS files and the dependencies.

对于日期范围选择,我们将使用bootstrap-daterangepicker 。 首先,我们包括CSS和JS文件以及相关性。

// views/home.blade.php
<div class="form-group">
            <label class="col-sm-3 control-label" for="">Date range</label>
            <div class="daterange col-md-9">
              <input name="daterange" class="form-control" value="2013-01-01 - 2014-12-30">
            </div>
          </div>

We create the the date range component.

我们创建日期范围组件。

// views/home.blade.php

$('input[name="daterange"]').daterangepicker({
	   format: 'YYYY-MM-DD',
	   startDate: '2013-01-01',
	   endDate: '2013-12-31'
});

In our aaa@qq.com method we used the last month as our range date.

在我们的aaa@qq.com方法中,我们使用上个月作为范围日期。

$now = new DateTime();
$end_date = $now->format('Y-m-d');
$start_date = $now->modify('-1 month')->format('Y-m-d');

Instead, we’re going to pass the start and end date as a parameter to the method after retrieving them on our aaa@qq.com.

相反,我们将在aaa@qq.com上检索开始日期和结束日期作为参数传递给方法。

$daterange = explode( ' - ', Input::get('daterange') );
$start_date = $daterange[0];
$end_date = $daterange[1];

$report = $this->ga->report( $view, $start_date, $end_date, $dimensions, $metrics );

Google Analytics API v3和PHP:过滤器和图表

最高结果 (Max results)

Our demo is taking only 10 results. We can make that configurable, or take it as a user input. The downside of this is the response becoming slow and taking too much to load, so you need to be prudent when using it.

我们的演示仅获得10个结果。 我们可以使它可配置,或者将其作为用户输入。 不利的一面是响应速度变慢并且加载过多,因此在使用时必须谨慎。

<div class="form-group">
              <label class="col-sm-3 control-label" for="">Max results</label>
              <div class="col-md-9">
                  <input name="max_results" type="text" class="form-control" value="10">
              </div>
          </div>

After adding the input to our form, we can receive the max_results parameter in our aaa@qq.com method and pass it to the aaa@qq.com method.

在将输入添加到表单后,我们可以在aaa@qq.com方法中接收max_results参数,并将其传递给aaa@qq.com方法。

// aaa@qq.com
$max_results = intval( Input::get('max_results') );
$report = $this->ga->report( $view, $start_date, $end_date, $max_results, $dimensions, $metrics );
// aaa@qq.com
$options['max-results'] = $max_results;
$data = $analytics->data_ga->get( $view, $start_date, $end_date, $metrics,
				$options
			);

筛选器 (Filters)

In this section, we’re trying to filter the response using the selected dimensions and metrics.

在本节中,我们尝试使用选定的维度和指标来过滤响应。

Example:

例:

ga:country aaa@qq.com (Only show countries that contain the word morocco)

ga:country aaa@qq.com (仅显示包含单词摩洛哥的国家)

尺寸过滤器 (Dimensions filter)

In the previous part we explained how filters work:

在上一部分中,我们解释了过滤器如何工作:

ga:column operator value

So, we need to create the list of dimensions, a select option for the operator and an input for the value to be used in the filter.

因此,我们需要创建维度列表,用于运算符的选择选项以及用于过滤器的值的输入。

Google Analytics API v3和PHP:过滤器和图表

We also added a select for show or don’t show rule.

我们还为展示或不展示规则添加了选择。

Back on the server side, we need to catch the user input. We can use JS to group the variable being sent to the server, but I’m trying to avoid any JS or ajax usage to keep the things server side.

回到服务器端,我们需要捕获用户输入。 我们可以使用JS对发送到服务器的变量进行分组,但是我试图避免使用任何JS或Ajax来将事情保留在服务器端。

I created a new file called GA_utils in our app/src folder. This is we’re we can put miscellaneous functions.

我在我们的app/src文件夹中创建了一个名为GA_utils的新文件。 这是我们可以放置其他功能的地方。

When posting the form this way, the request variables should look something like:

以这种方式发布表单时,请求变量应类似于:

array(11) {
  ...
  ["dimension_filter_show"]=>
  array(2) {
    [0]=>
    string(4) "show"
    [1]=>
    string(5) "dshow"
  }
  ["dimension_filters"]=>
  array(2) {
    [0]=>
    string(10) "ga:keyword"
    [1]=>
    string(9) "ga:medium"
  }
  ["dimension_filter_rules"]=>
  array(2) {
    [0]=>
    string(7) "contain"
    [1]=>
    string(6) "regexp"
  }
  ["dimension_filter_values"]=>
  array(2) {
    [0]=>
    string(6) "azerty"
    [1]=>
    string(7) "morocco"
  }
}

To group each index with the matching ones, we use the following function.

为了将每个索引与匹配的索引分组,我们使用以下函数。

// app/src/GA_utils.php

public static function groupFilters(array $show, array $filters, array $rules, array $values){
    $count = count($filters);
    $group_filters = [];

    for( $i = 0; $i < $count; $i++ ){
        // skip if no value is provided
        if( empty($values[$i]) )
            continue;

        $group_filters[] = [
            'show'      =>  $show[$i],
            'column'    => $filters[$i],
            'rule'      => $rules[$i],
            'val'       => $values[$i]
        ];
    }//for

    return $group_filters;
}//groupFilters

Now the result should become.

现在结果应该变成了。

array(2) {
  [0]=>
  array(4) {
    ["show"]=>
    string(4) "show"
    ["column"]=>
    string(10) "ga:keyword"
    ["rule"]=>
    string(7) "contain"
    ["val"]=>
    string(6) "azerty"
  }
  [1]=>
  array(4) {
    ["show"]=>
    string(5) "dshow"
    ["column"]=>
    string(9) "ga:medium"
    ["rule"]=>
    string(6) "regexp"
    ["val"]=>
    string(7) "morocco"
  }
}

Now that we have a clean input from the user we can proceed to encode the filters before sending them.

现在,我们收到了用户的明确输入,我们可以在发送过滤器之前继续对其进行编码。

public static function encodeDimensionFilters( $filters ){
   $url = [];

   foreach ($filters as $filter) {
       $operator ="";
       if( $filter['rule'] == "contain" ){
           if( $filter['show'] == "show" )
               $operator = 'aaa@qq.com';
           else
               $operator = 'aaa@qq.com';
       }
       else if( $filter['rule'] == "exact" ){
           if( $filter['show'] == "show" )
               $operator = '==';
           else
           $operator = '!=';
       }
       else if( $filter['rule'] == "regexp" ){
           if( $filter['show'] == "show" )
               $operator = '=~';
           else
               $operator = '!~';
       }

       $url[] = "{$filter['column']}{$operator}{$filter['val']}";
   }//foreach

   $uri = implode( ";", $url );
   //$uri = urlencode($uri);

   return $uri;
}//encodeDimensionFilters

This function will take the previous filter array and encode it as ga:column operator value. It will separate them using a semicolon (which means and – a comma is or).

此函数将采用先前的过滤器数组并将其编码为ga:column operator value 。 它将使用分号将它们分开(这意味着and -逗号为or )。

At this point, our aaa@qq.com method will use previous methods.

此时,我们的aaa@qq.com方法将使用以前的方法。

$filters = [];
$group_filters = [];
$group_filters['dimensions'] = GA_Utils::groupFilters(                        	Input::get('dimension_filter_show'),                          Input::get('dimension_filters'),                       Input::get('dimension_filter_rules'),				                                                     Input::get('dimension_filter_values')
);
        
$filters[] = GA_Utils::encodeDimensionFilters( $group_filters['dimensions'] );

You can visit the documentation for more in depth explanation.

您可以访问文档以获取更深入的解释。

Before testing the filters, I will create the necessary code for the metrics filter and we can test everything at once.

在测试过滤器之前,我将为指标过滤器创建必要的代码,我们可以立即测试所有内容。

指标过滤器 (Metrics filter)

The metrics filter is the same as the dimensions one, except that the columns are from a metrics list and the operators are mathematical.

指标过滤器与维度1相同,除了这些列来自指标列表并且运算符是数学的。

$group_filters['metrics'] = GA_Utils::groupFilters(
            Input::get('metric_filter_show'),
            Input::get('metric_filters'),
            Input::get('metric_filter_rules'),
            Input::get('metric_filter_values')
        );
        $filters[] = GA_Utils::encodeMetricFilters( $group_filters['metrics'] );

$filters = implode(';', $filters);

After getting and encoding the filters we implode the dimension and metric filter with a semicolon (and operator).

在获取并编码过滤器后,我们使用分号( and运算符)对维度和指标过滤器进行内插。

NOTE: dimension and metric filters cannot be combined using a comma (or operator).

注意:尺寸和公制过滤器不能使用逗号( or运算符)组合。

Now our filter should give us something like:

现在我们的过滤器应该给我们类似的东西:

// show countries containing the word morocco and page views are greater than 100

ga:aaa@qq.com;ga:pageviews>100

We will add the encoded filter and pass it to the aaa@qq.com as a parameter.

我们将添加编码的过滤器,并将其作为参数传递给aaa@qq.com

Google Analytics API accepts the encoded filter as an option, like max_results, etc.

Google Analytics API接受编码过滤器作为选项,例如max_results等。

// app/src/aaa@qq.com
$options['filters'] = $filters;

Google Analytics API v3和PHP:过滤器和图表

I got this result without using a filter.

我没有使用过滤器就得到了这个结果。

Google Analytics API v3和PHP:过滤器和图表

In this screenshot I’m using a filter:

在此屏幕截图中,我正在使用过滤器:

  • Don’t show (not set) country!

    不显示(not set)国家/地区!

  • Show only page views greater than 10.

    仅显示大于10的页面浏览量。

订购结果 (Ordering results)

Google Analytics gives us a nice way to sort results:

Google Analytics(分析)为我们提供了一种对结果进行排序的好方法:

ga:country,-ga:pageviews

We can order by dimensions or metrics. In our demo, I will use only one select list containing all metrics and dimensions.

我们可以按维度或指标进行排序。 在我们的演示中,我将仅使用一个包含所有指标和维度的选择列表。

// app/views/home.blade.php

<div class="col-md-7 nopadding">
	<select class="filter_columns form-control" name="orderbys[]">
        @foreach( $dimensions as $key => $group )
          <optgroup label="{{ $key }}" >
          @foreach( $group as $dimension )
            <option value="{{ $dimension->id }}">{{ $dimension->attributes->uiName }}</option>
          @endforeach
          </optgroup>
        @endforeach

        @foreach( $metrics as $key => $group )
          <optgroup label="{{ $key }}" >
          @foreach( $group as $metric )
            <option value="{{ $metric->id }}">{{ $metric->attributes->uiName }}</option>
          @endforeach
          </optgroup>
        @endforeach
    </select>
</div>

<div class="col-md-4 nopadding">
    <select class="form-control" name="orderby_rules[]">
        <option value="">ASC</option>
        <option value="-">DESC</option>
    </select>
</div>

After submitting the form we need to group and encode the list of order by rules.

提交表单后,我们需要按规则对订单列表进行分组和编码。

// app/src/GA_Utils.php

public static function groupOrderby(array $orderbys, array $rules){
    $count = count($orderbys);
    $group_orderbys = [];

    for( $i = 0; $i < $count; $i++ ){
        $group_orderbys[] = [
            'column'        =>  $orderbys[$i],
            'rule'          => $rules[$i]
        ];
    }//for

    return $group_orderbys;
}//groupOrderby

public static function encodeOrderby( $orderbys ){
    $res = [];

    foreach( $orderbys as $orderby ){
        $res[] = $orderby['rule'] . $orderby['column'];
    }//foreach

    return implode( ',', $res );
}//encodeOrderby

Inside our aaa@qq.com we will encode our order by inputs.

aaa@qq.com内部,我们将通过输入对订单进行编码。

// app/controllers/aaa@qq.com

$orderbys = GA_Utils::encodeOrderby( GA_Utils::groupOrderby(Input::get('orderbys'), Input::get('orderby_rules') ) );

Google Analytics API accepts the encoded order by as an option.

Google Analytics(分析)API作为选项接受编码顺序

// app/src/aaa@qq.com

$options['sort'] = $orderbys;

Google Analytics API v3和PHP:过滤器和图表

In this screenshot, I eliminated the (not set) country and sorted by country. You can read more about sorting results in the docs.

在此屏幕截图中,我消除了(not set)国家/地区,并按国家/地区进行了排序。 您可以在docs中阅读有关排序结果的更多信息。

使用图表 (Using charts)

This part is not related to Google Analytics API, but if you’re using the Google Analytics Service, you noticed those fancy charts. In this part, I will be using Highcharts, and I will use the pie chart example from their demo.

这部分与Google Analytics(分析)API不相关,但是如果您使用的是Google Analytics(分析)服务,则会注意到这些花哨的图表。 在这一部分中,我将使用Highcharts ,并将使用其demo中的饼图示例。

To draw a pie chart we need a name and a y axis array.

要绘制饼图,我们需要一个name和一个y轴数组。

[
	{
		"name":"(not set)",
		"y":"1"
	},
	{
		"name":"Argentina",
		"y":"4"
	},
	{
		"name":"Belgium",
		"y":"15"
	},
	{
		"name":"Brazil",
		"y":"104"
	}
	...
]

Let’s start by adding a new select option list containing a pie and table chart options.

首先,添加一个包含饼图和表格图表选项的新选择选项列表。

On our server, we will only create a JSON representation of our report data.

在我们的服务器上,我们将仅创建报告数据的JSON表示形式。

$json_data = [];
foreach( $report['items'] as $item ){
    $json_data[] = [
        'name'  => $item[0],
        'y'     => $item[1]
    ];
}//foreach

return View::make('report', [
		'columns'       => $report['columnHeaders'],
        'items'         => $report['items'],
        'totalResults'  => $report['totalResults'],
        'report_json'   => json_encode($json_data),
        'chart_type'    => Input::get('chart_type')
]);

The only remaining part is to catch those values inside our view. We test if the user wants a table or a pie .

剩下的唯一部分是在我们的视图中捕获这些值。 我们测试用户是否想要桌子或馅饼。

@if( $chart_type == 'pie' )
<div class="pie">
    <div id="pie_canvas"></div>
</div>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script>
     $(function(){
         var el = $("#pie_canvas"),
             serie_data = {{ $report_json }};
      el.highcharts({
          chart: {
              plotBackgroundColor: null,
              plotBorderWidth: 1,
              plotShadow: false
          },
          title: {
              text: ''
          },
          tooltip: {
              pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
          },
          plotOptions: {
              pie: {
                  allowPointSelect: true,
                  cursor: 'pointer',
                  dataLabels: {
                      enabled: true,
                      format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                      style: {
                          color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                      }
                  },
                  showInLegend: true
              }
          },
          series: [{
                      type: 'pie',
                      name: '',
                      data: serie_data
                  }]
      });//highchart
 });
</script>
@else
	// print the table here
@endif

First, we include the highchart.js file, then we use some configuration from their documentation. The important part is the serie_data = {{ $report_json }}. Inside our controller, we created an array of values, and then we encoded those values to be used in our JS.

首先,我们包含highchart.js文件,然后使用其文档中的一些配置。 重要的部分是serie_data = {{ $report_json }} 。 在我们的控制器内部,我们创建了一个值数组,然后对这些值进行编码以在JS中使用。

Note: when choosing the pie chart you need to choose only one metric and one dimension, or you would have to extend the demo and use the drill down functionality provided by highchart.

注意:选择饼形图时,您只需选择一个度量标准和一个维度,否则您将不得不扩展演示并使用highchart提供的向下钻取功能。

Running the previous code will give a result like this.

运行前面的代码将得到这样的结果。

Google Analytics API v3和PHP:过滤器和图表

结论 (Conclusion)

In this part, we explored some more of Google Analytics API, demonstrating its power and customizability. Most of the API is used on the Google Analytics Query Explorer and can be explored that way. Let me know what you think about the API and this tutorial, and feel free to check out the final repo to test the demo.

在这一部分中,我们探索了更多Google Analytics API,展示了其强大功能和可定制性。 大多数API在Google Analytics(分析)查询浏览器上使用 ,可以通过这种方式进行浏览。 让我知道您对API和本教程的看法,并随时查看最终回购以测试演示。

翻译自: https://www.sitepoint.com/google-analytics-api-v3-php-filters-charts/