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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP fputcsv() to Write CSV Files

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"
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPfile I/OCSVfputcsv
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.