How creating a report with dimensionFilter and matchType in PHP ? (GA4)

Viewed 904

I am trying to use Google Analytics Data API v1 with PHP. I imported google/analytics-data with composer, then set up the whole API correctly and I get all my pages with the views. But I need to filter the results based on the URL with filters.

    $client = new BetaAnalyticsDataClient();
    $response = $client->runReport([
        'property' => 'properties/' . $property_id,
        'dateRanges' => [
            new DateRange([
                'start_date' => '2021-01-01',
                'end_date' => 'today',
            ]),
        ],
        'dimensions' => [new Dimension(
            [
                'name' => 'pagePath',
            ]
        ),
        ],
        'metrics' => [new Metric(
            [
                'name' => 'screenPageViews',
            ]
        )
        ],
        'dimensionFilter' => [new DimensionExpression(
            [
                'filter' => [new filter(
                    [
                    'stringFilter' => [new stringFilter([
                        'value' => '/orders/',
                        'match_type' => 'BEGINS_WITH'
                        ]
                    )]
                    ]
                )]
            ]
        )]

    ]);

but how add a dimensionFilter ?

"dimensionFilter": {
    "filter": {
      "stringFilter": {
        "value": "/orders/",
        "matchType": "BEGINS_WITH"
      },
      "fieldName": "pagePath"
    }
  }

The result is :

An uncaught Exception was encountered Type: UnexpectedValueException

Message: Invalid message property: stringFilter

Filename: ...vendor\google\protobuf\src\Google\Protobuf\Internal\Message.php

2 Answers

It works.

'dimensionFilter' => new FilterExpression([
  'filter' => new Filter([
    'field_name' => 'pagePath',
    'string_filter' => new Filter\StringFilter([
      'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH,
      'value' => '/orders/',
     ])
  ])
]),

Try something like that:

'dimensionFilter' => new FilterExpression([
    'filter' => new Filter([
        'field_name' => 'pagePath',
        'string_filter' => new StringFilter([
            'value' => '/orders/',
            'match_type' => 'BEGINS_WITH'
        ])
    ])
])
Related