How to export csv file in codeigniter

by ryan.murray , in category: PHP Frameworks , 10 months ago

How to export csv file in codeigniter

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 6 months ago

@ryan.murray 

To export a CSV file in CodeIgniter, you can follow these steps:

  1. Create a function in your controller to generate the CSV data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public function export_csv() {
    $this->load->dbutil();
    $this->load->helper('file');

    $query = $this->db->query("SELECT * FROM your_table");
    $delimiter = ",";
    $newline = "
";

    $data = $this->dbutil->csv_from_result($query, $delimiter, $newline);

    // Set the file name
    $file_name = 'export.csv';

    write_file($file_name, $data);

    // Download file
    $this->load->helper('download');
    force_download($file_name, NULL);
}


  1. Create a route in your routes file to access this function:
1
$route['export-csv'] = 'YourController/export_csv';


  1. Create a link in your view file to trigger the CSV export:
1
<a href="<?php echo base_url('export-csv'); ?>">Export CSV</a>


  1. When you click on the "Export CSV" link, it will generate a CSV file containing the data from the specified table and prompt the user to download it.


That's it! You have successfully exported a CSV file in CodeIgniter.