How to Formats a line as CSV and writes it to an open file in PHP ?
To format a line as CSV and write it to an open file in PHP, you can use the fputcsv()
function. This function formats a line as CSV and writes it to an open file pointer. Here's an example:
// Open the file for writing
$file = fopen('data.csv', 'w');
// Write the header row
$header = ['Name', 'Email', 'Phone'];
fputcsv($file, $header);
// Write the data rows
$data = [
['John Doe', '[email protected]', '555-1234'],
['Jane Smith', '[email protected]', '555-5678'],
['Bob Johnson', '[email protected]', '555-9012'],
];
foreach ($data as $row) {
fputcsv($file, $row);
}
// Close the file
fclose($file);
In this example, we first open a file called data.csv
for writing. We then write the header row as an array using fputcsv()
. Next, we loop through an array of data rows and write each row to the file using fputcsv()
. Finally, we close the file using fclose()
.
The resulting data.csv
file will look like this:
Name,Email,Phone
John Doe,[email protected],555-1234
Jane Smith,[email protected],555-5678
Bob Johnson,[email protected],555-9012
Note that fputcsv()
automatically adds the necessary commas and quotes to format the data as CSV. If any of the data contains commas or quotes, fputcsv()
will automatically escape them.