PHP CSV Files

Su Subhalakshmi Chandran Updated 05 Nov 2026
7 min read ·Lesson 248 of 248

What Is a CSV File?

In simple terms: A CSV (Comma-Separated Values) file stores a table as plain text: one row per line, with values separated by commas. Spreadsheet programs such as Excel, Google Sheets, and LibreOffice can open and save CSV files, which makes CSV the most common format for importing and exporting data.

id,name,price
1,Gel Pen,20
2,Notebook,60

Technically: CSV is described in RFC 4180. Values containing the separator, double quotes, or line breaks are wrapped in double quotes, and double quotes inside values are doubled (""). PHP's fgetcsv(), fputcsv(), and str_getcsv() implement these rules, so you should never split or build CSV lines manually with explode() and implode().

Why Not Just Use explode(',')?

<?php
$line = '1,"Desk Lamp, LED",1299';

print_r(explode(',', $line));
print_r(str_getcsv($line, escape: ''));

Output

Array
(
    [0] => 1
    [1] => "Desk Lamp
    [2] =>  LED"
    [3] => 1299
)
Array
(
    [0] => 1
    [1] => Desk Lamp, LED
    [2] => 1299
)

explode() breaks the quoted product name into two broken fields. str_getcsv() understands the quotes and returns the correct three values.


The escape Parameter

PHP's CSV functions historically used a non-standard backslash escape character (0), which can corrupt data containing backslashes. Since **PHP 8.4**, relying on the default value of the $escapeparameter is **deprecated**. Passescape: ''` (an empty string) to get standard RFC 4180 behavior — all examples in this lesson do so.


Writing CSV: fputcsv()

Syntax

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

Example

<?php
$products = [
    ['id', 'name', 'price'],
    [1, 'Desk Lamp, LED', 1299],
    [2, 'Notebook "A5"', 60],
    [3, 'Gel Pen', 20],
];

$file = __DIR__ . '/products.csv';
$handle = fopen($file, 'w');

foreach ($products as $row) {
    fputcsv($handle, $row, escape: '');
}

fclose($handle);

echo file_get_contents($file);

Output

id,name,price
1,"Desk Lamp, LED",1299
2,"Notebook ""A5""",60
3,Gel Pen,20

What fputcsv() Did

  • Desk Lamp, LED contains a comma, so it is wrapped in quotes.
  • Notebook "A5" contains quotes, so it is wrapped in quotes and each inner quote is doubled.
  • Simple values are written without quotes.

fputcsv() returns the length of the written line, or false on failure.


Reading CSV: fgetcsv()

Example

<?php
$handle = fopen(__DIR__ . '/products.csv', 'r');

$header = fgetcsv($handle, escape: '');
$total = 0;

while (($row = fgetcsv($handle, escape: '')) !== false) {
    $product = array_combine($header, $row);
    $total += (int) $product['price'];

    echo "{$product['id']}: {$product['name']} — ₹{$product['price']}\n";
}

fclose($handle);

echo "Total: ₹$total\n";

Output

1: Desk Lamp, LED — ₹1299
2: Notebook "A5" — ₹60
3: Gel Pen — ₹20
Total: ₹1379

How It Works

  1. The first fgetcsv() call reads the header row.
  2. Each later call reads one row as an array of strings, decoding quotes correctly. At the end of the file, it returns false.
  3. array_combine($header, $row) turns each row into an associative array keyed by column name, so the code reads $product['price'] instead of $row[2].
  4. All values are strings; convert them ((int), filter_var()) before calculating.

Because fgetcsv() reads one row at a time, this works for files of any size. (A blank line is returned as [null]; array_combine() would throw a ValueError for it, so real imports should skip or report rows whose column count does not match the header.)

Other Separators

Many European spreadsheets export CSV with semicolons, and tab-separated files (TSV) are also common:

$row = fgetcsv($handle, separator: ';', escape: '');
$row = fgetcsv($handle, separator: "\t", escape: '');

Practical Example: Importing With Validation

Imported data must be validated like any other user input. Reporting errors with line numbers lets the user fix the file:

<?php
$csv = <<<CSV
name,email,score
Asha,asha@example.com,88
Bala,bala@,72
Charu,charu@example.com,abc
"Dev, R",dev@example.com,95
CSV;

file_put_contents(__DIR__ . '/students.csv', $csv . "\n");

function importStudents(string $path): array
{
    $handle = fopen($path, 'r');
    if ($handle === false) {
        throw new RuntimeException("Cannot open $path");
    }

    $header = fgetcsv($handle, escape: '');
    $valid = [];
    $errors = [];
    $line = 1;

    while (($row = fgetcsv($handle, escape: '')) !== false) {
        $line++;

        if (count($row) !== count($header)) {
            $errors[] = "Line $line: expected " . count($header) . " columns";
            continue;
        }

        $record = array_combine($header, array_map('trim', $row));

        if (filter_var($record['email'], FILTER_VALIDATE_EMAIL) === false) {
            $errors[] = "Line $line: invalid email '{$record['email']}'";
            continue;
        }

        $score = filter_var($record['score'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 100]]);
        if ($score === false) {
            $errors[] = "Line $line: score must be 0–100";
            continue;
        }

        $valid[] = ['name' => $record['name'], 'email' => $record['email'], 'score' => $score];
    }

    fclose($handle);

    return [$valid, $errors];
}

[$students, $errors] = importStudents(__DIR__ . '/students.csv');

echo "Imported: " . implode(', ', array_column($students, 'name')) . "\n";
echo implode("\n", $errors) . "\n";

Output

Imported: Asha, Dev, R
Line 3: invalid email 'bala@'
Line 4: score must be 0–100

Step-by-Step Explanation

  1. The header is line 1, so the line counter starts at 1 and increases before each data row.
  2. Rows with the wrong number of columns are reported instead of crashing array_combine().
  3. Each field is trimmed and validated; invalid rows are collected with their line number.
  4. Valid rows are converted to typed values (the score becomes an int).
  5. "Dev, R" is read correctly as one name, thanks to the quotes.

A real import would then insert the valid rows into the database inside a transaction, and show the errors to the user.


Exporting CSV for Download

To let users download a CSV file directly, write to php://output with the right headers:

<?php
// export-orders.php
$orders = [
    ['id' => 101, 'customer' => 'Asha', 'total' => 1250],
    ['id' => 102, 'customer' => 'பாலா', 'total' => 640],
];

header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="orders-2026-10-15.csv"');

$output = fopen('php://output', 'w');

fwrite($output, "\xEF\xBB\xBF");   // UTF-8 BOM so Excel shows Tamil text correctly

fputcsv($output, ['Order ID', 'Customer', 'Total'], escape: '');
foreach ($orders as $order) {
    fputcsv($output, [$order['id'], $order['customer'], $order['total']], escape: '');
}

fclose($output);
exit;

How It Works

  • Content-Disposition: attachment makes the browser download the response as a file with the given name.
  • php://output is a stream that writes directly to the response, so rows are sent as they are generated — even for very large exports — without building the whole file in memory.
  • The UTF-8 byte order mark (EF BB BF) helps Excel recognize UTF-8, so non-English text such as Tamil names is displayed correctly instead of as garbled characters.

Security: CSV (Formula) Injection

When exported data is opened in a spreadsheet, a cell starting with =, +, -, or @ may be interpreted as a formula. An attacker who enters a "name" like =HYPERLINK("http://evil.example","Click") can create a malicious link in an administrator's export. Neutralize such values when exporting user-supplied data:

<?php
function csvSafe(mixed $value): mixed
{
    if (is_string($value) && $value !== '' && in_array($value[0], ['=', '+', '-', '@', "\t", "\r"], true)) {
        return "'" . $value;
    }

    return $value;
}

$output = fopen('php://output', 'w');
fputcsv($output, array_map('csvSafe', ['=HYPERLINK("http://evil.example","Click")', 'Asha', 1250]), escape: '');
fclose($output);

Output

"'=HYPERLINK(""http://evil.example"",""Click"")",Asha,1250

The leading apostrophe makes spreadsheets treat the value as text. Apply this only to text that came from users; numbers (including negative ones) can be passed through unchanged, as here.


SplFileObject for CSV

<?php
$file = new SplFileObject(__DIR__ . '/products.csv');
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD | SplFileObject::DROP_NEW_LINE);
$file->setCsvControl(',', '"', '');

foreach ($file as $index => $row) {
    if ($index === 0) {
        continue;   // header
    }
    echo $row[1] . "\n";
}

Output

Desk Lamp, LED
Notebook "A5"
Gel Pen

READ_CSV makes the iterator return parsed rows; setCsvControl() sets the separator, enclosure, and (empty) escape character. The flags skip the empty line at the end of the file.


Common Mistakes

Splitting CSV With explode()

Effect: Quoted values containing commas are broken apart.

Fix: Use fgetcsv() or str_getcsv().

Building CSV Lines by Hand

Effect: Values with commas, quotes, or line breaks corrupt the file.

Fix: Use fputcsv().

Relying on the Default escape

Effect: Backslashes in data are mishandled; deprecation notices in PHP 8.4+.

Fix: Pass escape: ''.

Trusting Imported Data

Effect: Invalid or malicious values enter the database.

Fix: Validate every row and report errors with line numbers.

Loading Huge Files Into Memory

Effect: Memory exhaustion with file() or file_get_contents() + str_getcsv().

Fix: Read row by row with fgetcsv() and write exports to a stream.


Best Practices

  • Use fgetcsv()/fputcsv() with escape: '' for standard-compliant CSV.
  • Map rows to the header with array_combine() after checking column counts.
  • Validate imported rows like form input, and report errors by line number.
  • Stream large imports and exports instead of building arrays in memory.
  • Add a UTF-8 BOM for Excel users, and neutralize formula characters in exported user data.

Official reference: https://www.php.net/manual/en/function.fgetcsv.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about PHP CSV Files and get answers drawn from it.

Signed-in readers only.