Building CSV with array

13,004

Solution 1

Here's some code I use... you could adjust the columns you need in the export...

Note: This CSV is directly sent to php://output which writes directly to the output buffer. This means you're not saving any .csv files on the server and it can handle a much larger file size that building a giant array and then trying to loop through it.

    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=\"Jobs_".date('M.j.y', $from)."-".date('M.j.y', $to).".csv\"");
    header("Pragma: no-cache");
    header("Expires: 0");

    $handle = fopen('php://output', 'w');
    fputcsv($handle, array(
        'JobId',
        'Template',
        'Customer',
        'Status',
        'Error',
        'PDF',
        'Run Time',
        'Wait Time',
        'Server'
    ));

    foreach ($jobs as $jobData) {
        fputcsv($handle, array(
            $job->getId(),
            $job->getTemplate(),
            $jobData['customers_firstname'].' '.$jobData['customers_lastname'],
            $status,
            $error,
            $jobData['products_pdfupload'],
            $job->getRunTime(),
            $job->getWaitTime(),
            $jobData['server']
        ));
    }

    fclose($handle);
    exit;

This should give you a good mental picture of how a CSV export works. I don't use CodeIgniter's file download helper, so I can't help you on that front.

Solution 2

This short scripts build the CSV and allows you to download it also:

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
    /** open raw memory as file, no need for temp files */
    $temp_memory = fopen('php://memory', 'w');
    /** loop through array */
    foreach ($input_array as $line) {
        /** default php csv handler **/
        fputcsv($temp_memory, $line, $delimiter);
    }
    /** rewrind the "file" with the csv lines **/
    fseek($temp_memory, 0);
    /** modify header to be downloadable csv file **/
    header('Content-Type: application/csv');
    header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
    /** Send file to browser for download */
    fpassthru($temp_memory);
}

/** Array to convert to csv */
$array_to_csv = Array(Array(12566, 'Enmanuel', 'Corvo'), Array(56544, 'John', 'Doe'), Array(78550, 'Mark', 'Smith'));
convert_to_csv($array_to_csv, 'report.csv', ',');

You can read the full post here:

PHP Array to CSV - Download

Solution 3

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>
Share:
13,004
Dylan Buth
Author by

Dylan Buth

Updated on June 17, 2022

Comments

  • Dylan Buth
    Dylan Buth almost 2 years

    I need to run a query that will return multiple rows and export it to a CSV. I have to put the cells in a certain order though.

    So lets say my table is laid out id, name, address, wife. I need to build a csv in the order of id, address, wife, name. I figured I could just make an array in the correct order and then make a csv with that but after an hour of googling i cant find out how to make a csv with an array.

    There is fputcsv but that requires a pre-made csv. Also, i was hoping there was a codeigniter way of doing it.

     public function export() {
        $this->load->helper('download');
    
        $data[1] = 'i like pie';
        $data[2] = 'i like cake';
        force_download('result.csv', $data);  
    }
    

    I tried that but the error said the download helper file was expecting a string not an array.