Creating downloadable CSV file in PHP

This time I would like to share you how to automatically download CSV file using PHP.

To download CSV file, the header() function and the php://output parameter must be used.

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=myCSV.csv');
header("Content-Transfer-Encoding: UTF-8");

Setting the header is importance when downloading files automatically. In the first line of code, the content-type option is that HTTP header telling the browser that the MIME type of the content is application/csv.

Other particularly important option is in the second line of code, the filename option. This is where we want to name the file that will be generated and downloaded.

The other importance line of code is content transfer encoding ,this encoding method will transform binary email message data into the US-ASCII plain text format.

For populating CSV, fopen() giving us access to PHP’s output buffer. This line of code is that the file pointer connected to the output stream.

$f = fopen('php://output', 'a'); 

Writing data to the Csv and we can define column headings like this:

fputcsv($f, array('Column 1', 'Column 2', 'Column 3'));

We can fetch data and loop over the rows of data and output them.

mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

while ($row = mysql_fetch_assoc($rows)) fputcsv($f, $row);

By Ami



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム