building csv with array

building csv with array  using -'php,arrays,codeigniter,csv,download'

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() {

    $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.

asked Sep 15, 2015 by VickiNevile
0 votes

3 Answers

0 votes

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(
        'Run Time',
        'Wait Time',

    foreach ($jobs as $jobData) {
        fputcsv($handle, array(
            $jobData['customers_firstname'].' '.$jobData['customers_lastname'],


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.

answered Sep 15, 2015 by MajorBlakele
0 votes

answered Sep 15, 2015 by RanSwenson
0 votes

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 */

/** 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

answered Sep 15, 2015 by ShelliBarrie