I want to generate a csv file, using data from a database. How does one do this in PHP CodeIgniter framework?
Asked
Active
Viewed 2.6k times
-1
-
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 Answers
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.
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
-
I used Reports in codeigniter link code but it does not updating my csv. I mentioned CSV file path like this write_file(base_url().'public/csv_file.csv',$new_report); – Serma Oct 30 '13 at 06:58
-
what do you want to do? generate new csv file or update the existing one – Muhammad Raheel Oct 30 '13 at 07:02
-
-
where i have to write this function csv_from_result($report), this was mentioned in codeigniter controller like $new_report = $this->dbutil->csv_from_result($report); – Serma Oct 30 '13 at 07:11
-
this need to be written in controller as mentioned in example. Just you have to give the correct path. use constant `APPPATH` and concat where you want to write file – Muhammad Raheel Oct 30 '13 at 07:29
-
Thanks man it works fine but is it posible to create new csv file at everytime – Serma Oct 30 '13 at 07:38
-
why not. every time when ever this controller method is called you need to give new name or you can generate a random name like this `'generated_csv_'.time().'csv'`. this will always generate file with new name due to php `time()`. – Muhammad Raheel Oct 30 '13 at 08:08
-
-
write_file(APPPATH . 'generated_csv_'.time().'csv',$new_report); I used this but not generating any new file – Serma Oct 30 '13 at 08:59
-
it should be something like this `write_file(APPPATH . '/views/csv/'.'generated_csv_'.time().'csv',$new_report)` – Muhammad Raheel Oct 30 '13 at 09:01
-
-
-
-
-
@Serma don't you think an answer should be accepted or voted up – Muhammad Raheel Nov 01 '13 at 06:34