使用 fputcsv 将 JSON 变量保存到 csv

Save a JSON variable to a csv using fputcsv

我从 Adob​​e Analytics 中提取了一份报告,并尝试将结果保存在 csv 文件中。这是我的代码和描述:

<?php
include_once('/path/SimpleRestClient.php');

// Creation of csv filepath 
$adobe_file = $sql_path = '/path/adobe.csv';

// List creation that will be updated with the fields and be put into my CSV file
$list = array 
    (
        array('page','page_views') // headers 
    );

class API
{
    // Get it form the platform after logging in, User icon, settings 
    private $username       = "XXXXX"; 
    private $shared_secret  = "XXXXX";
    private $postURL        = "https://api3.omniture.com/admin/1.4/rest/?method="; 

    private function _request($m, $o) {     
        $nonce      = md5(uniqid(php_uname('n'), true));
        $nonce_ts   = date('c');
        $digest     = base64_encode(sha1($nonce . $nonce_ts . $this->shared_secret));

        $rc         = new SimpleRestClient();
        $rc         -> setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$this->username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
        //var_dump($o);
        $rc         -> postWebRequest($this->postURL . $m, $o);     
        return $rc;
    }

    private function _queue($o)
    {
        return $this -> _request('Report.Queue', $o);
    }

    private function _get($o, $sleep = 120)
    {
        $counter    = 0; 
        do
        {
            if($counter>0){sleep($sleep);}
            $rc = $this -> _request('Report.Get', $o);      
            $counter++;
        }while($rc -> getStatusCode() == 400 && json_decode($rc->getWebResponse())->error == 'report_not_ready');

        return $rc;
    }

    public function get($rsid, $dates, $granularity, $metrics, $elements, $segments)
    {

        if($granularity == 'week')
        {
            $date   = '"dateFrom":"' . $dates['from'] . '",
                       "dateTo":"' . $dates['to'] . '",
                       "dateGranularity":"week",';
        }
        else
        {
            $date   = '"date":"' . $dates['from'] . '",
                       "dateGranularity":"' . $granularity . '",';  
        }

        $reportDescription  = '{
                                    "reportDescription":
                                    {
                                        "reportSuiteID":"' . $rsid . '",
                                        ' . $date . '
                                        "metrics":' . $metrics . ',
                                        "elements":' . $elements . ',
                                        "segments":' . $segments . '
                                    }
                                }';

        $queuedReport   = $this->_queue($reportDescription);

        if($queuedReport -> getStatusCode() == 200)
        {
            return $this -> _get($queuedReport -> getWebResponse());
        }   
        return $queuedReport;
    }

    public function get_async( $wait = 15)
    {

        $reportDescription      ='{
            "reportDescription":{
                "reportSuiteID":"XXXXX",
                "dateFrom":"2015-11-01",
                "dateTo":"2015-11-30",
                "metrics":[{"id":"pageviews"}],
                "elements":[{"id":"page","top":"25"}]
            }
           }';

        $queuedReport = $this->_queue($reportDescription);

        if($queuedReport -> getStatusCode() == 200)
        {
            $return = $this -> _get($queuedReport -> getWebResponse(),$wait);
        }
        else
        {
            $return = $queuedReport;
        }

        return $return;
    }
}

$myclass = new API;
$output = $myclass->get_async(); 

现在我想将 Adob​​e Analytics 报告的输出传递到 csv 文件。通常,我使用此代码:

$fp = fopen($adobe_file, 'w');

while ($row = mysql_fetch_row($output)) {
        $marks = json_decode($row['responsesJSON'],true);
        unset($row['responsesJSON']);
        fputcsv($fp, array_merge(array_values($row),array_values($marks))); //
    }

    fclose($fp);

但在这种情况下,输出是一个 JSON 变量。 我的 csv 文件是空的 因为列表是空的。有了 1.3,我可以轻松做到。

删除功能更好,因为不需要使用多个 php 文件。因此,代码的工作原理如下:

    <?php

include_once('path/SimpleRestClient.php');

// Creation of CSV filepath 
$adobe_file = 'path/Adobe.csv';

// List creation that will be updated with the fields and be put into my CSV file
$list = array 
    (
        array('page','page_views') // headers // ADD or DELETE metrics #
    );

function GetAPIData($method, $data) 
{
    $username       = "XXXXX"; 
    $shared_secret  = "XXXXX";
    $postURL        = "https://api3.omniture.com/admin/1.4/rest/?method=";  

    // Nonce is a simple unique id to each call to prevent MITM attacks.
    $nonce      = md5(uniqid(php_uname('n'), true));
    // The current timestamp in ISO-8601 format
    $nonce_ts   = date('c');
    // The Password digest is a concatenation of the nonce, its timestamp and your password (from the same location as your username) which runs through SHA1 and then through a base64 encoding    
    $digest     = base64_encode(sha1($nonce . $nonce_ts . $shared_secret));

    $rc = new SimpleRestClient();    
    $rc -> setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
    //var_dump($o);

    $rc -> postWebRequest($postURL .$method, $data);    
    return $rc;
}

$method = 'Report.Queue';   
$data       ='
            {
                "reportDescription":
                {
                "reportSuiteID":"XXXXX",
                "dateFrom":"2015-11-01",
                "dateTo":"2015-11-30",
                "metrics":[{"id":"pageviews"}], 
                "elements":[{"id":"page","top":"25"}]
                }
            }';

$rc=GetAPIData($method, $data);

if($rc -> getStatusCode() == 200) // status code 200 is for 'ok'
{
    $counter    = 0; 
    do
    {
        if($counter>0){sleep($sleep = 120);}
        $return = GetAPIData('Report.Get', $rc -> getWebResponse());
        $counter++;
    }while($return -> getStatusCode() == 400 && json_decode($return->getWebResponse())->error == 'report_not_ready'); // status code 400 is for 'bad request'

        // valto 2
    $json=json_decode($return->getWebResponse());

    foreach ($json->report->data as $el) 
    {
        echo $el->name.":".$el->counts[0]."\n";

        // Adding the data in the CSV file without overwriting the previous data
        array_push($list, array($el->name, $el->counts[0]));
    }   

// xe valto 2 
}
else
{
    $return = $queuedReport;
}

$fp = fopen($adobe_file, 'w');

foreach ($list as $fields) 
{
    // save rows to the CSV file
    fputcsv($fp, $fields);
}

fclose($fp);

?>