Example 1 — Write a Small CSV File
Write a header row and two data rows, then print the file.
<?php
$file = __DIR__ . '/people.csv';
$fp = fopen($file, 'w');
fputcsv($fp, ['name', 'city']);
fputcsv($fp, ['Asha', 'Chennai']);
fputcsv($fp, ['Ravi', 'Mumbai']);
fclose($fp);
echo file_get_contents($file);
unlink($file); How It Works
- fopen() opens a new CSV file for writing.
- Each fputcsv() call turns one array into one line of comma separated text.
- fclose() saves and closes the file.
- file_get_contents() reads the file back so we can print it.

