I want to generate a csv file, using data from a database. How does one do this in PHP CodeIgniter framework?
2
-
This might help, once you have your query turned into an array: stackoverflow.com/questions/16251625/…Resorath– Resorath2013-10-30 06:18:01 +00:00Commented Oct 30, 2013 at 6:18
-
possible duplicate of Reports in CodeigniterMuhammad Raheel– Muhammad Raheel2013-10-30 06:41:25 +00:00Commented Oct 30, 2013 at 6:41
Add a comment
|
2 Answers
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
15 Comments
Serma
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);
Muhammad Raheel
what do you want to do? generate new csv file or update the existing one
Serma
I want to generate new csv
Serma
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);
Muhammad Raheel
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 |
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;
}
1 Comment
Pratik Joshi
Stop using
mysql_* and OP used Codeigniter, not core php.