Skip to content
Advertisement

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.

The application has a newsletter subscription system. I make use of a table named newsletter with 3 columns: id, email and subscription_date.

In the class Subscribers controller, I have created an export() method intend to export subscribers as a CSV file:

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:

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

The problem

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?

Advertisement

Answer

Ok, here’s what I found by replicating your code to a fresh install of Codeigniter.

  1. Created a “files” directory on project root
  2. I’ve autoloaded the “database” library and the “url” helper;
  3. Created a newsletter table, as described by you, using mockaroo;
  4. I’m not considering the request headers, download or redirect, as they didn’t seemed wrong to me
  • Nothing was changed on the Newsletter_model, just on the controller.

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:

  1. Your model returns an Array with objects. So, your $row will be a object.
  2. fputcsv expects an Array as a second parameter, just like you did with the $header

I think this will work for you. 🙂

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement