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.
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 (\).
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']
];
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>
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.
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
Arrays Must Be One-Dimensional: fputcsv() only accepts one-dimensional arrays. If you have multidimensional arrays, process them row by row.
File Permission Issues: Ensure the PHP script has write permissions for the target directory; otherwise, fopen() will fail.
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.