Import and export CSV files with PHP

Intermediate  Nov 3, 2026

Download a table as CSV and read an uploaded CSV safely.

Import and export CSV files with PHP
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

Export

<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="customers.csv"');

$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");                       // BOM so Excel reads UTF-8
fputcsv($out, ['ID', 'Name', 'Email']);

foreach ($pdo->query('SELECT id, name, email FROM customers') as $row) {
    fputcsv($out, $row);
}
fclose($out);
How the code in this section fits into the page.
How the code in this section fits into the page.

Import

<?php
$tmp = $_FILES['csv']['tmp_name'] ?? '';
if (!is_uploaded_file($tmp)) exit('No file');

$h = fopen($tmp, 'r');
fgetcsv($h);                                         // skip header row
$stmt = $pdo->prepare('INSERT INTO customers (name, email) VALUES (?, ?)');

$pdo->beginTransaction();
while (($row = fgetcsv($h)) !== false) {
    if (count($row) < 2) continue;
    if (!filter_var($row[1], FILTER_VALIDATE_EMAIL)) continue;
    $stmt->execute([trim($row[0]), trim($row[1])]);
}
$pdo->commit();
fclose($h);

Tips

  • Use fputcsv and fgetcsv. Splitting on commas yourself breaks when a value contains a comma or a quote.
  • A transaction makes the import all-or-nothing and much faster.
  • Spreadsheet programs run text starting with =, +, - or @ as formulas. When exporting user text, prefix such values with a '.
The main points of this section.
The main points of this section.

More tutorials