-1

I want to generate a csv file, using data from a database. How does one do this in PHP CodeIgniter framework?

DreadPirateShawn
  • 8,164
  • 4
  • 49
  • 71
Serma
  • 44
  • 1
  • 2
  • 11
  • This might help, once you have your query turned into an array: http://stackoverflow.com/questions/16251625/how-to-create-and-download-a-csv-file-from-php-script – Resorath Oct 30 '13 at 06:18
  • possible duplicate of [Reports in Codeigniter](http://stackoverflow.com/questions/11189021/reports-in-codeigniter) – Muhammad Raheel Oct 30 '13 at 06:41

2 Answers2

1
function query_to_csv( $query, $filename, $attachment = false, $headers = true) {

    if($attachment) {
        // send response headers to the browser
        header( 'Content-Type: text/csv' );
        header( 'Content-Disposition: attachment;filename='.$filename);
        $fp = fopen('php://output', 'w');
    } else {
        $fp = fopen($filename, 'w');
    }

    $result = mysql_query($query);

    if($headers) {
        // output header row (if at least one row exists)
        $row = mysql_fetch_assoc($result);
        if($row) {
            fputcsv($fp, array_keys($row));
            // reset pointer back to beginning
            mysql_data_seek($result, 0);
        }
    }

    while($row = mysql_fetch_assoc($result)) {
        fputcsv($fp, $row);
    }

    fclose($fp);
    exit;
}
Asif
  • 647
  • 9
  • 18
1

Take a look at this answer of mine and you will know exactly how you can do it.

Reports in Codeigniter

You need to use Codeigniter Database Utility Class

And need to return query instead of result_array or result

Community
  • 1
  • 1
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103