Using PHP fputcsv() to Write CSV Files
This article explains how the PHP fputcsv() function formats an array as a CSV line and writes it to a file, detailing its parameters, return value, and providing a complete example with code and the resulting CSV output.
The fputcsv() function formats a single row—provided as an array—to CSV format and writes it to a file handle opened with fopen(). It is a convenient way to generate CSV files directly from PHP.
Parameters : handle: a valid file pointer obtained from fopen() or fsockopen() that has not been closed. fields: an array containing the values for the CSV row. delimiter (optional): a single‑character string that separates fields (default is a comma). enclosure (optional): a single‑character string used to enclose fields (default is a double‑quote).
The function returns the length of the written string on success, or FALSE on failure.
Example :
<?php
$list = array(
array('aaa','bbb','ccc','dddd'),
array('123','456','789')
);
$fp = fopen('file.csv','w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>This script creates a CSV file file.csv containing the following output:
aaa,bbb,ccc,dddd
123,456,789
"","aaa","bbb"Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
