将Google Analytics Reporting API结果作为XML / JSON返回

时间:2018-03-09 20:01:18

标签: php json xml google-analytics google-analytics-api

不是PHP开发人员,但需要从Analytics Reporting API V4 using PHP获取报告。如果有人能帮我转换xml或json格式的结果,我会很感激。我无法将使用示例代码中的printResults($ reports)函数检索到的结果插入到数据库中。谢谢!

3 个答案:

答案 0 :(得分:0)

Google_Service_AnalyticsReporting_GetReportsResponse Object
(
    [collection_key:protected] => reports
    [reportsType:protected] => Google_Service_AnalyticsReporting_Report
    [reportsDataType:protected] => array
    [internal_gapi_mappings:protected] => Array
        (
        )

    [modelData:protected] => Array
        (
            [reports] => Array
                (
                    [0] => Array
                        (
                            [columnHeader] => Array
                                (
                                    [dimensions] => Array
                                        (
                                            [0] => ga:dimension9
                                            [1] => ga:campaign
                                            [2] => ga:source
                                            [3] => ga:medium
                                            [4] => ga:keyword
                                            [5] => ga:adContent
                                        )

                                    [metricHeader] => Array
                                        (
                                            [metricHeaderEntries] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [name] => organicSearches
                                                            [type] => INTEGER
                                                        )

                                                )

                                        )

                                )

                            [data] => Array
                                (
                                    [rows] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [dimensions] => Array
                                                        (
                                                            [0] => 1000342194.1520628512
                                                            [1] => (not set)
                                                            [2] => google
                                                            [3] => organic
                                                            [4] => (not provided)
                                                            [5] => (not set)
                                                        )

以上是print_r($ response)的结果;基于该对象,我使用以下函数以XML格式打印响应:

function printResultsAsXml($response) {
    $array = $response['reports'];
    $arrayHeaders = ($array[0]['columnHeader']['dimensions']);

    $arrayRows = $array[0]['data']['rows'];
    $mdarray = array();

    for ( $rowIndex = 0; $rowIndex < count($arrayRows); $rowIndex++) { 
        $mdarray[] = array_combine($arrayHeaders, $arrayRows[$rowIndex]['dimensions']);
    }

    // print_r(xmlutils::array_to_xml($mdarray));
    $output = xmlutils::array_to_xml($mdarray);

    header('content-type: text/xml');

    $doc = new DOMDocument();
    $doc->loadXML($output, LIBXML_NOXMLDECL);
    echo $doc->saveXML();
}

以下是XML中的结果。我是PHP的新手,所以如果你碰巧知道更好的答案,请告诉我。

<data>
    <data-item>
        <gadimension9>1000342194.1520628512</gadimension9>
        <gacampaign>(not set)</gacampaign>
        <gasource>google</gasource>
        <gamedium>organic</gamedium>
        <gakeyword>(not provided)</gakeyword>
        <gaadContent>(not set)</gaadContent>
    </data-item>
    <data-item>
        <gadimension9>1000401494.1520637016</gadimension9>
        <gacampaign>(not set)</gacampaign>
        <gasource>google</gasource>
        <gamedium>organic</gamedium>
        <gakeyword>(not provided)</gakeyword>
        <gaadContent>(not set)</gaadContent>
    </data-item>
</data>

xmlutils.php由Jeremy Pyne编写,用于将数组转换为xml。

如果代码抛出这样的错误:

DOMDocument::loadXML(): xmlParseEntityRef: no name in Entity. 

这很可能是由于&#39;&amp;&#39;性格,应该被替换。我根据这个question的答案向xmlutils.php添加了一行。

$value=preg_replace('/&(?!#?[a-z0-9]+;)/', '&amp;', $value);

答案 1 :(得分:0)

xml的答案变得很长,所以我将把json部分分开。 Json处理特殊字符,例如'&amp;'更好。如果您使用SQL Server 2016或更高版本,则使用OPENJSON要容易得多。但是,我们有一台带有SQL Server 2014的远程服务器,所以我必须使用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));
}

更新:之前的答案仅获取维度,此答案可以获取指标并将2个多维数组合并为一个 - PHP: Merge 2 Multidimensional Arrays

答案 2 :(得分:0)

不知道为什么,但是我在使用@kakugiki的函数时遇到了一些有趣的错误-数组的大小不相等,还有其他问题。

如果其他人对此有有趣的结果,我会改写一下,对于我来说,这似乎很可靠。

 public function result($reports)
{
    $rows=[];

    foreach($reports as $report) {
        $header = $report->getColumnHeader();
        $dimensionHeaders = $header->getDimensions();
        $metricHeaderEntries = $header->getMetricHeader()->getMetricHeaderEntries();
        $rows = array_merge($rows, $report->getData()->getRows());
    }

    foreach($metricHeaderEntries as $metricHeaderEntry) {
        $metricHeaders[] = $metricHeaderEntry->getName();
    }

    $headers = array_merge($dimensionHeaders, $metricHeaders);

    foreach($rows as $row) {
        $metrics = [];
        $dimensions = $row->getDimensions();
        $metricEntries = $row->getMetrics();
        foreach($metricEntries as $metricEntry) {
            $metrics = array_merge($metrics, $metricEntry->getValues());
        }

        $results[] = array_combine($headers, array_merge($dimensions, $metrics));
    }

    return $results;

}