phpcsvadobearray-pushfputcsv

Save a JSON variable to a csv using fputcsv


I pull a report from Adobe Analytics and I am trying to save the results in a csv file. Here is my code with a description :

<?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(); 

Now I want to pass the output of the Adobe Analytics report to a csv file. Generally, I use this code :

$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);

but in this case the output is a JSON variable. My csv file is empty because the list is empty. With 1.3 I could do it easily.


Solution

  • Removing the functions is better because there is no need to use more than one php files. So, the code works as following :

        <?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);
    
    ?>