为什么我不能在此 Codeigniter 应用程序中将 MySQL table 值导出为 CSV 文件?

Why can't I export MySQL table values as a CSV file in this Codeigniter application?

我一直在使用 CodeIgniter 3.1.8 和 Twig 开发博客应用程序。

该应用程序有一个时事通讯订阅系统。我使用了一个名为 newsletter 的 table,包含 3 列:idemailsubscription_date.

在 class Subscribers 控制器中,我创建了一个 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'); 
}

Newsletter_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();
}

导出形式:

<?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(); ?>

问题

由于我无法弄清楚的原因,仅导出 table headers,而不导出值(电子邮件和日期) .

我做错了什么?

好的,这是我通过将您的代码复制到全新安装的 Codeigniter 中得到的结果。

  1. 在项目根目录中创建了一个“文件”目录
  2. 我已经自动加载了“数据库”库和“url”助手;
  3. 如您所述,使用 mockaroo 创建了简报 table;
  4. 我不考虑 header 请求、下载或重定向,因为它们对我来说似乎没有错
  • Newsletter_model 上没有任何变化,只是在控制器上。

这是我的 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);

发生的事情是:

  1. 您的模型 returns 一个包含 object 的数组。因此,您的 $row 将是 object.
  2. fputcsv 需要一个数组作为第二个参数,就像您对 $header
  3. 所做的一样

我认为这对你有用。 :)