Write PHP Array to CSV using fputcsv

This article provides a quick guide on how to export PHP arrays into a CSV file using the native fputcsv() function. You will learn the step-by-step process of opening a file, looping through your data array, writing the formatted CSV lines, and properly closing the file stream.

The fputcsv() function in PHP formats a line as CSV and writes it to an open file pointer. This is the most efficient way to generate CSV files because it automatically handles formatting, such as adding delimiters and enclosing fields that contain spaces or special characters.

Step-by-Step Implementation

To write an array to a CSV file, follow these three steps:

  1. Open the file using fopen() with the write mode ('w').
  2. Loop through the array and pass each row to fputcsv().
  3. Close the file using fclose() to free up system resources.

Code Example

Here is a complete, ready-to-use PHP script that demonstrates how to write a multidimensional array to a CSV file:

<?php

// 1. Prepare the data array (including headers)
$data = [
    ['ID', 'Name', 'Email', 'Role'],
    [1, 'John Doe', 'john@example.com', 'Administrator'],
    [2, 'Jane Smith', 'jane@example.com', 'Editor'],
    [3, 'Bob Johnson', 'bob@example.com', 'Subscriber']
];

// 2. Open the file in write mode
$filePath = 'users.csv';
$fileHandle = fopen($filePath, 'w');

if ($fileHandle === false) {
    die('Cannot open the file ' . $filePath);
}

// 3. Loop through the array and write each row to the CSV file
foreach ($data as $row) {
    fputcsv($fileHandle, $row);
}

// 4. Close the file handle
fclose($fileHandle);

echo "CSV file created successfully!";

Understanding the fputcsv() Parameters

The fputcsv() function accepts up to five parameters:

fputcsv($stream, array $fields, string $separator = ",", string $enclosure = '"', string $escape = "\\")