Search code examples
phpjsonxmlgoogle-analyticsgoogle-analytics-api

Return Google Analytics Reporting API result as XML/JSON


Not a PHP developer, but need to get a report from the Analytics Reporting API V4 using PHP. I'd appreciate it if anyone can help me to convert the result in xml or json format. I am having trouble to insert the result, retrieved using the function printResults($reports) from the sample code, into a database. Thank you!


Solution

  • The answer for xml is getting real long so I'll put the json part separately. Json handles special character such as '&' better. If you using SQL server 2016 or later, then using OPENJSON is much easier. However, we have a remote server with SQL server 2014 so I have to use xml.

    function printResultsAsJson($reports) {
        $darray = array();
        $marray = array();
        $mkey = array();
    
        for ($reportIndex = 0; $reportIndex < count($reports); $reportIndex++) {
            $report = $reports[$reportIndex];
            $header = $report->getColumnHeader();
            $dimensionHeaders = $header->getDimensions();
            $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
            $rows = $report->getData()->getRows();
    
            for ($j = 0; $j < count($metricHeaders); $j++) {
                $entry = $metricHeaders[$j];
                $mkey[] = $entry->getName();
            }
    
            for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
                $row = $rows[$rowIndex];
                $dimensions = $row->getDimensions();
                $metrics = $row->getMetrics();
    
                $darray[] = array_combine($dimensionHeaders, $dimensions);
    
                for ($j = 0; $j < count($metrics); $j++) {
                    $values = $metrics[$j]->getValues();
                    $marray[] = array_combine($mkey, $values);
                }
            }
    
        }
    
        $i = 0;
        $mdarray = array();
        foreach($darray as $value) {
            $mdarray[] = array_merge($value, $marray[$i]);
            $i++;
        }
    
        print_r(json_encode($mdarray));
    }
    

    Update: previous answer gets the dimensions only, this one is able to get metrics and merge 2 multidimensional arrays into one - PHP: Merge 2 Multidimensional Arrays.