CSV stands for Comma Separated Values. This file format is commonly used to store data, export data from database etc.
In this tutorial, i will demostrate how to create download CSV file in PHP.
How to Create Download CSV File
Let’s first create a CSV with one record, then we move to more values. Now we are creating CSV with following header and one record
Id, Name, Branch, UniqueID
1, Revenue, Account,456
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
$delimiter = ","; // Comma separated // File name is start.csv $filename = "start.csv"; $data = array('Id', 'Name', 'Branch','UniqueID'); $string = implode($delimiter, $data); print $string . "\r\n"; header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=$filename"); header("Pragma: no-cache"); header("Expires: 0"); // Put some data $value = array(1, 'Revenue', 'Account',456); $dataRowString = implode($delimiter, $value); print $dataRowString . "\r\n"; exit(); |
header(‘Content-Disposition: attachment; filename=$filename’);
This header tells the browser that this file should be download with a filename we mention instead of displaying on browser.
Process Multiple Records
Now consider a case in which you are pulling the data from database. So instead of one records you have an array of multiple records.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
$delimiter = ","; // Comma separated // File name intialized $filename = "multiple_records.csv"; // Record Header $data = array('Id', 'Name', 'Branch','UniqueID'); $string = implode($delimiter, $data); print $string . "\r\n"; header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=$filename"); header("Pragma: no-cache"); header("Expires: 0"); // Process an array // $data_values is an array of multiple records foreach ($data_values as $key => $value) { if(!empty($value)){ $emp_data['id'] = $value['id']; $emp_data['name'] = $value['name']; $emp_data['branch'] = $value['branch']; $emp_data['unique_id'] = $value['unique_id']; $dataRowString = implode($delimiter, $emp_data); print $dataRowString . "\r\n"; } }exit(); |