PHP

CSV Writer with Proper Escaping

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Write rows to a CSV file using fputcsv with sensible quoting. Also writes a UTF-8 BOM so Excel opens the file with the right encoding.
PHP
Raw
<?php
function writeCsv(string $path, array $header, iterable $rows): int {
    $fh = fopen($path, 'w');
    if (!$fh) throw new RuntimeException("Cannot open $path for writing");
    fwrite($fh, "\xEF\xBB\xBF");           // UTF-8 BOM — keeps Excel happy
    fputcsv($fh, $header);
    $count = 0;
    foreach ($rows as $row) {
        fputcsv($fh, array_map(fn($v) => $v ?? '', $row));
        $count++;
    }
    fclose($fh);
    return $count;
}

writeCsv('export.csv', ['id', 'name', 'email'], [
    [1, 'Alice', 'a@x.com'],
    [2, 'Bob',   'b@x.com'],
]);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.