In this tutorial, you will learn how to export PHP array data to a CSV file, a process that can be integral to automated accounting systems. The data to export can be from any data source like a database table. The steps are as follows:
Let’s say we have an array of data in PHP, this data can be from any data source like a database table. For example, we have two fields of employees: name and salary. This can be an associative array.
$data = array(
array('Jane', 2500),
array('Paul', 2000),
array('Jake', 3000),
array('Tim', 3500),
);
Now, we will define the file name as ’employees.csv’ and delimiter as a comma.
$filename = 'employees' . '.csv';
$delimiter = ',';
Next, open the file pointer with write mode (‘w’). ‘php://memory’ represents that we are opening the file in php memory.
$f = fopen('php://memory', 'w');
The first row in the CSV file contains the heading columns (name and salary).
$headings = array('name', 'salary');
Next, we use fputcsv to write these heading columns to the file. Here, we also specify the delimiter (comma);
fputcsv($f, $headings, $delimiter);
Similarly, we can loop through all the data array and write to the same file.
foreach($data as $row) {
fputcsv($f, $row, $delimiter);
}
Now, we will set the position of the file pointer using fseek. The fseek() function moves the file pointer from its current position to a new position, forward or backward specified by the number of bytes.
fseek($f, 0);
Next, we will set the response headers to export the CSV file.
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
Now, output all remaining data on a file pointer.
fpassthru($f);
Lastly, close the file pointer and exit.
fclose($f);
exit();
The code for exporting the CSV file is as follows:
<?php
$data = array(
array('Jane', 2500),
array('Paul', 2000),
array('Jake', 3000),
array('Tim', 3500),
);
$filename = 'employees' . '.csv';
$delimiter = ',';
$f = fopen('php://memory', 'w');
$headings = array('name', 'salary');
fputcsv($f, $headings, $delimiter);
foreach($data as $row) {
fputcsv($f, $row, $delimiter);
}
fseek($f, 0);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($f);
fclose($f);
exit();
If you don’t know how to import a CSV file, you can follow this tutorial: How to Import Data from CSV File using PHP