SyntaxStudy
Sign Up
PHP Intermediate 8 min read

CSV File Handling

CSV (Comma-Separated Values) is one of the most common data exchange formats. PHP has built-in functions specifically for reading and writing CSV that handle quoting, escaping, and delimiters correctly.

  • fgetcsv() reads one row at a time from an open file handle.
  • fputcsv() writes an array as a properly escaped CSV row.
  • str_getcsv() parses a CSV string (useful for single lines from APIs).
Example
<?php
// Reading a CSV file
$csvPath = '/var/data/users.csv';
$handle  = fopen($csvPath, 'r');

if ($handle === false) {
    throw new RuntimeException("Cannot open $csvPath");
}

$headers = fgetcsv($handle); // First row = headers
$users   = [];

while (($row = fgetcsv($handle)) !== false) {
    if (count($row) !== count($headers)) continue; // skip malformed
    $users[] = array_combine($headers, $row);
}
fclose($handle);

foreach ($users as $user) {
    printf("Name: %s, Email: %s
", $user['name'], $user['email']);
}

// Writing a CSV file
$outputPath = '/var/data/export.csv';
$handle     = fopen($outputPath, 'w');

// UTF-8 BOM for Excel compatibility
fwrite($handle, "\xEF\xBB\xBF");

// Write header row
fputcsv($handle, ['ID', 'Name', 'Email', 'Registered']);

// Write data rows
$data = [
    [1, 'Alice Smith',  'alice@example.com',  '2024-01-15'],
    [2, 'Bob O'Brien',  'bob@example.com',    '2024-02-20'],
    [3, 'Carol Davis',  'carol@example.com',  '2024-03-05'],
];
foreach ($data as $row) {
    fputcsv($handle, $row);
}
fclose($handle);

// Parse a CSV string
$line = 'John,"Doe, Jr.",john@example.com';
$cols = str_getcsv($line);
print_r($cols); // ['John', 'Doe, Jr.', 'john@example.com']
Pro Tip

Tip: When exporting CSV for Microsoft Excel, prepend the UTF-8 BOM (\"\xEF\xBB\xBF\") before the first row. Without it, Excel often misinterprets non-ASCII characters in the default encoding.