Write PHP Array to CSV File

PHP is fully capable of writing to many files that are needed for various development tasks. One of which is writing a full data set from an array to a comma-separated value export. There are plenty of libraries out there that can achieve this task but most are full of bloat and take a lot longer than the native functions available.

In this tutorial, we will learn how to convert an array, both associative and indexed to a comma-separated value output.

Associative Array To CSV Method

In the associative method, we need will use the associative identifiers as the files column headers and then write in the values that belong to them

PHP Code

$f = fopen('mycsv.csv', 'a'); // Configure fopen to create, open, and write data.

fputcsv($f, array_keys($data[0])); // Add the keys as the column headers

// Loop over the array and passing in the values only.
foreach ($data as $row)
{
    fputcsv($f, $row);
}
// Close and initiate download.
fclose($f);

 

Breakdown of the code –

  • First, we use the fopen() function to open the file and write to it. This uses two parameters
    • ‘mycsv.csv’ – Essentially the identifying name and full path – This will create the file in the same directory as the script.
    • ‘a’  to instruct fopen to create the file if it doesn’t exist and instruct that we are wanting to write only.
  • Then we need to add the initial array headers or column headers. We do this by using fputcsv() outside the loop, just passing in the keys.
  • From here we start to loop over the entire array calling to fputcsv() again but only passing in the ‘rows’ or values.
  • Finally, we instruct PHP to close the file, and after this is executed, the comma-seperated value typed-file will be downloaded to our local machine.

 

Indexed Array To CSV Method

This method takes less code than the above method due to no keys being present so therefore we don’t need to worry about them. In this use case, we only loop in the actual values.

PHP Code

$f = fopen('mycsv.csv', 'a'); // Configure fOpen to create, open and write only.

// Loop over the array and passing in the values only.
foreach ($data as $row)
{
    fputcsv($f, $row);
}
// Close and initiate download.
fclose($f);

 

Breakdown of the code –

  • First, we use the fopen() function to open the file and write to it. This uses two parameters
    • ‘mycsv.csv’ – Essentially the identifying name and full path and full path – This will create in the same directory as the script.
    • ‘a’  to instruct fopen to create if it doesn’t exist and instruct that we are wanting to write only.
  • From here we start to loop over the entire indexed array calling to fputcsv() passing in each value.
  • Finally, we instruct PHP to close the file, and after this is executed it will be downloaded to our local machine.

Automatically Download The File Generated

In each of the two methods in this tutorial, files that are created are saved to the directory of the script. But what if we want the file to download or export automatically? We can add headers() to the script which will carry out the task.

Add the following to the array to tutorial scripts above and the file will download as myCSV.csv

PHP Code

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

 

Saving The File To Sub-Directory

To create and store the comma-separated value to a sub-directory of choice, you simply need to define this in the fopen() function. Also, important note, if the directory doesn’t exist, you must create it first. You could achieve this manually or programmatically with a function like mkdir.

If we were to save the comma-separated file-type to an existing directory named files, it would be something like below –

$f = fopen('files/mycsv.csv', 'a');

Function References

 

Summary

In this tutorial we explored the native capabilities of PHP, using file-writing functions that allow us to quickly convert array-data into specified file-types. PHP is more than capable of doing these jobs and doing so extremely quickly.

SHARE ON

The Author: Dan Englishby

Write PHP Array to CSV File
Posted in PHP

You May Also Like

Leave a Reply

Your email address will not be published.