php create and download a csv file

PHP – Create and Download a CSV File

Avatar photoPosted by

Introduction:

A Comma Separated Values (CSV) file is a plain text file where the values are separated by comma. CSV file usually stores tabular data(text, number or dates). CSV file is the most common format for data-exchange or transferring tabular data between programs.

Most of the web application used CSV file to import and export data. It is a common feature today for an application to have CSV import/export function. This blog will teach yout how to create and download a CSV file. We will be using PHP in this tutorial. PHP is the most popular and widely used scripting-language that is very suited for web developement.

Source Code:

This is the full source code:

<?php


// filename
$filename = 'myfile.csv';
// open file to write
$file = fopen($filename, 'w');
// column names array
$columns = ['USERNAME', 'PASSWORD'];
// write the columns
fputcsv($file, $columns);

//column data arrays
$credentials = [
	['username1', 'password1'],
	['username2', 'password2'],
	['username3', 'password3'],
	['username4', 'password4'],
	['username5', 'password5']
];

// loop the column data arrays
foreach ($credentials as $row) 
{
	// write the data
	fputcsv($file, $row);
}

fclose($file);
header('Content-type: text/csv');
header('Content-disposition:attachment; filename="'.$filename.'"');
readfile($filename);

?>

Procedures:

Step 1: Create CSV File

The fopen() function will open or create a file if the file does note exist. The fopen() function has 4 parameters fopen( $filename, $mode, $include_path, $context), $filename and $mode are required parameters. We will assign a filename and set the mode to w (Write Only).

$filename = 'myfile.csv';
$file = fopen($filename, 'w');

Step 2: Write Data On File

The fputcsv() function will format a line as csv and write it to the open file. The fputcsv() function has 5 parameters fputcsv($file, $fields, $separator, $enclosure, $escape), $file and $fields are required parameters. We will assign the created file as the $file parameter. The $fields parameter is an array of values. We will write first column names array and then write the column data array. Then, close the file

// column names array
$columns = ['USERNAME', 'PASSWORD'];
// write the columns
fputcsv($file, $columns);

//column data arrays
$credentials = [
	['username1', 'password1'],
	['username2', 'password2'],
	['username3', 'password3'],
	['username4', 'password4'],
	['username5', 'password5']
];

// loop the column data arrays
foreach ($credentials as $row) 
{
	// write the data
	fputcsv($file, $row);
}
fclose($file);

Step 3: Download Script

Last add a code to download the csv file. The code will tell the browser that download a csv file.

//
header('Content-type: text/csv');
header('Content-disposition:attachment; filename="'.$filename.'"');
readfile($filename);