[英]Why can't I export MySQL table values as a CSV file in this Codeigniter application?
I have been developing a blogging application with CodeIgniter 3.1.8 and Twig.我一直在使用 CodeIgniter 3.1.8 和 Twig 开发博客应用程序。
The application has a newsletter subscription system.该应用程序有一个时事通讯订阅系统。 I make use of a table named newsletter with 3 columns:
id
, email
and subscription_date
.我使用了一个名为newsletter的表,它有 3 列:
id
、 email
和subscription_date
。
In the class Subscribers controller, I have created an export()
method intend to export subscribers as a CSV file:在 class订阅者controller 中,我创建了一个
export()
方法,打算将订阅者导出为 CSV 文件:
public function export(){
$data = $this->Static_model->get_static_data();
$subscribers = $this->Newsletter_model->fetchSubscribers();
$file_name = 'subscribers_'.date('Ymd').'.csv';
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Type: application/csv;");
// CSV creation
$file = fopen('php://output', 'w');
$header = array("Email", "Subscription Date");
fputcsv($file, $header);
foreach ($subscribers as $key => $value) {
fputcsv($file, $value);
}
fclose($file);
redirect('dashboard/subscribers');
}
In the Newsletter_model model:在Newsletter_model model 中:
public function fetchSubscribers() {
$this->db->select('email, subscription_date');
$this->db->order_by('newsletter.id', 'DESC');
$query = $this->db->get('newsletter');
return $query->result();
}
The export form :出口形式:
<?php echo form_open(base_url('dashboard/subscribers/export'), ['class' => 'ml-auto']); ?>
<button type="submit" class="btn btn-sm btn-success"><i class="fa fa-file mr-1"></i> Export CSV</button>
<?php echo form_close(); ?>
For a reason I have not been able to figure out, only the table headers are exported , not the values (emails and dates).出于某种原因,我无法弄清楚,只有表头被导出,而不是值(电子邮件和日期)。
What am I doing wrong?我究竟做错了什么?
Ok, here's what I found by replicating your code to a fresh install of Codeigniter.好的,这是我通过将您的代码复制到全新安装的 Codeigniter 中发现的。
Here's my export()这是我的导出()
$header = array("Email", "Subscription Date");
$subscribers = $this->newsletter->fetchSubscribers();
$file_name = 'subscribers_'.date('Ymd').'.csv';
$file = fopen(BASEPATH . '../files/' . $file_name, 'w');
fputcsv($file, $header);
foreach ($subscribers as $row) {
fputcsv($file, [$row->email, $row->subscription_date]);
}
fclose($file);
What happened is:发生的事情是:
I think this will work for you.我认为这对你有用。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.