Current Location: Home> Latest Articles> How to Correctly Write Array Data to a CSV File Using PHP's fputcsv Function? Step-by-Step Guide

How to Correctly Write Array Data to a CSV File Using PHP's fputcsv Function? Step-by-Step Guide

M66 2025-06-26

During development, CSV files are commonly used for data export and exchange. PHP offers a very convenient built-in function fputcsv() for writing array-formatted data into CSV files. This article will explain in detail how to use the fputcsv() function to correctly write arrays into a standard CSV file.

1. What is fputcsv?

fputcsv() is a PHP function designed to write array data into an open file resource in CSV format. It automatically handles necessary delimiters, quotes, newlines, and other formatting issues, avoiding errors that may come from manual string concatenation.

The function prototype is as follows:

fputcsv(resource $stream, array $fields, string $separator = ",", string $enclosure = "\"", string $escape = "\\"): int|false

Parameter explanations:

  • $stream: The file handle resource opened using fopen().

  • $fields: A one-dimensional array where each element represents a column in the CSV file.

  • $separator: The delimiter between fields, defaulting to a comma (,).

  • $enclosure: The character used to enclose field values, default is double quotes (").

  • $escape: The escape character, default is backslash (\).

2. Preparing the Data to Write

Suppose we have a set of user data that we want to write to a CSV file:

$data = [
    ['Username', 'Email', 'Registration Time'],
    ['Zhang San', 'zhangsan@m66.net', '2025-06-10 10:00:00'],
    ['Li Si', 'lisi@m66.net', '2025-06-10 11:20:00'],
    ['Wang Wu', 'wangwu@m66.net', '2025-06-10 12:35:00']
];

3. Complete Code Example for Writing to a CSV File

We want to write the above data into a file named users.csv:

<?php
<p>// Path to the CSV file to write<br>
$filename = 'users.csv';</p>
<p>// Open the file in write mode (creates the file if it doesn't exist)<br>
$fp = fopen($filename, 'w');</p>
<p>if ($fp === false) {<br>
die("Unable to open file: $filename");<br>
}</p>
<p>// Data to write<br>
$data = [<br>
['Username', 'Email', 'Registration Time'],<br>
['Zhang San', '<a class="cursor-pointer" rel="noopener">zhangsan@m66.net</a>', '2025-06-10 10:00:00'],<br>
['Li Si', '<a class="cursor-pointer" rel="noopener">lisi@m66.net</a>', '2025-06-10 11:20:00'],<br>
['Wang Wu', '<a class="cursor-pointer" rel="noopener">wangwu@m66.net</a>', '2025-06-10 12:35:00']<br>
];</p>
<p>// Loop through each row and write it to the file<br>
foreach ($data as $row) {<br>
fputcsv($fp, $row);<br>
}</p>
<p>// Close the file handle<br>
fclose($fp);</p>
<p>echo "CSV file has been written successfully.\n";<br>

4. Outputting to Browser for Download (Optional)

If you don't want to save the file on the server but want the user to download the CSV file directly, you can use the following method:

<?php
<p>header('Content-Type: text/csv');<br>
header('Content-Disposition: attachment; filename="users.csv"');</p>
<p>$fp = fopen('php://output', 'w');</p>
<p>$data = [<br>
['Username', 'Email', 'Registration Time'],<br>
['Zhang San', '<a class="cursor-pointer" rel="noopener">zhangsan@m66.net</a>', '2025-06-10 10:00:00'],<br>
['Li Si', '<a class="cursor-pointer" rel="noopener">lisi@m66.net</a>', '2025-06-10 11:20:00'],<br>
['Wang Wu', '<a class="cursor-pointer" rel="noopener">wangwu@m66.net</a>', '2025-06-10 12:35:00']<br>
];</p>
<p>foreach ($data as $row) {<br>
fputcsv($fp, $row);<br>
}</p>
<p>fclose($fp);<br>

By visiting the PHP file containing this code, the browser will prompt to download a file named users.csv with the data we prepared.

5. Common Issues and Notes

  1. Character Encoding Issues: The default output is UTF-8. If garbled text appears when opening in Excel, you can add a UTF-8 BOM header before outputting:

    echo "\xEF\xBB\xBF"; // Add BOM
    
  2. Arrays Must Be One-Dimensional: fputcsv() only accepts one-dimensional arrays. If you have multidimensional arrays, process them row by row.

  3. File Permission Issues: Ensure the PHP script has write permissions for the target directory; otherwise, fopen() will fail.

6. Conclusion

Using PHP’s fputcsv() function, we can easily write array-formatted data to CSV files, whether saving locally or offering direct download via browser. By preparing your data and using file handling functions correctly, you can achieve efficient and standardized data export functionality.