How to Write CSV File in PHP: Simple Guide with Examples
To write a CSV file in PHP, use the
fopen function to create or open a file, then write rows using fputcsv. Finally, close the file with fclose to save your data properly.Syntax
Here is the basic syntax to write a CSV file in PHP:
fopen(filename, mode): Opens a file for writing.fputcsv(file, array): Writes an array as a CSV row.fclose(file): Closes the file to save changes.
php
<?php $file = fopen('file.csv', 'w'); fputcsv($file, ['column1', 'column2']); fclose($file); ?>
Example
This example creates a CSV file named users.csv with four rows of user data.
php
<?php
$data = [
['Name', 'Email', 'Age'],
['Alice', 'alice@example.com', 30],
['Bob', 'bob@example.com', 25],
['Charlie', 'charlie@example.com', 35]
];
$file = fopen('users.csv', 'w');
foreach ($data as $row) {
fputcsv($file, $row);
}
fclose($file);
echo "CSV file 'users.csv' created successfully.";
?>Output
CSV file 'users.csv' created successfully.
Common Pitfalls
Common mistakes when writing CSV files in PHP include:
- Not closing the file with
fclose, which can cause data loss. - Using the wrong mode in
fopen(use'w'to write or overwrite). - Not handling special characters or commas inside data fields properly.
Always use fputcsv to handle escaping automatically.
php
<?php // Wrong way: forgetting fclose $file = fopen('wrong.csv', 'w'); fputcsv($file, ['data1', 'data2']); // fclose($file); // Missing fclose can cause issues // Right way: $file = fopen('right.csv', 'w'); fputcsv($file, ['data1', 'data2']); fclose($file); ?>
Quick Reference
| Function | Purpose |
|---|---|
| fopen(filename, mode) | Open or create a file for writing |
| fputcsv(file, array) | Write an array as a CSV row with proper escaping |
| fclose(file) | Close the file to save changes |
| 'w' mode | Open file for writing, overwrite if exists |
| 'a' mode | Open file for appending, add data at the end |
Key Takeaways
Use fopen with 'w' mode to create or overwrite a CSV file.
Write each row as an array using fputcsv for proper CSV formatting.
Always close the file with fclose to ensure data is saved.
Avoid manual string concatenation; fputcsv handles commas and quotes.
Check file permissions to avoid write errors.