使用 PHP Codeigniter 框架生成 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19675132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate CSV file using PHP Codeigniter Framework
提问by Serma
I want to generate a csv file, using data from a database. How does one do this in PHP CodeIgniter framework?
我想使用数据库中的数据生成一个 csv 文件。在 PHP CodeIgniter 框架中如何做到这一点?
回答by Praveen D
use csv_helper to generate csv file.
使用 csv_helper 生成 csv 文件。
Follow this below link to get solution,
按照以下链接获取解决方案,
http://www.code2learn.com/2012/03/generating-csv-file-using-codeigniter.html
http://www.code2learn.com/2012/03/generating-csv-file-using-codeigniter.html
回答by Asif
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;
}
回答by Muhammad Raheel
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
您需要使用Codeigniter 数据库实用程序类
And need to return query instead of result_array
or result
并且需要返回查询而不是result_array
或result