P
P
Petr Fronin2019-08-15 18:02:12
Google Analytics
Petr Fronin, 2019-08-15 18:02:12

How to get Google Analytics API 4 views for articles?

Faced the problem of getting the number of views for pages
This code:

$analytics = $this->initializeAnalytics();
        $response = $this->getReport($analytics);
        $this->printResults($response);

function initializeAnalytics()
    {
        $KEY_FILE_LOCATION = __DIR__ . '/file.json';

        // Create and configure a new client object.
        $client = new Google_Client();
        $client->setApplicationName("Hello Analytics Reporting");
        $client->setAuthConfig($KEY_FILE_LOCATION);
        $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
        $analytics = new Google_Service_AnalyticsReporting($client);

        return $analytics;
    }

    function getReport($analytics) {

        // Replace with your view ID, for example XXXX.
        $VIEW_ID = "XXX";

        // Create the DateRange object.
        $dateRange = new Google_Service_AnalyticsReporting_DateRange();
        $dateRange->setStartDate("7daysAgo");
        $dateRange->setEndDate("today");


        // Create the Metrics object.
        $sessions = new Google_Service_AnalyticsReporting_Metric();
        $sessions->setExpression("ga:pageviews");
        $sessions->setAlias("pageviews");

        // Create the DimensionFilter.
        $dimensionFilter = new Google_Service_AnalyticsReporting_DimensionFilter();
        $dimensionFilter->setDimensionName('ga:pagePath');
        $dimensionFilter->setOperator('EXACT');
        $dimensionFilter->setExpressions('/post/post1');


        // Create the DimensionFilterClauses
        $dimensionFilterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause();
        $dimensionFilterClause->setFilters(array($dimensionFilter));

        // Create the ReportRequest object.
        $request = new Google_Service_AnalyticsReporting_ReportRequest();
        $request->setViewId($VIEW_ID);
        $request->setDateRanges($dateRange);
        $request->setDimensionFilterClauses(array($dimensionFilterClause));
        $request->setMetrics(array($sessions));


        $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
        $body->setReportRequests( array( $request) );

        return $analytics->reports->batchGet( $body );
    }

Here we get the number of views for the last 7 days for the article '/post/post1'
I can't figure out how to get the whole list of articles with views
Something like:
'/post/post1' => 34
'/post/post2' => 854
' /post/post3' => 75

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2019-08-15
@dimonchik2013

little code
recommend to start with https://ga-dev-tools.appspot.com/query-explorer/
achieve required output and copy parameters

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question