Working with CSV in PHP: Reading, Writing, and Data Processing

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with CSV in PHP: A Complete Guide



CSV (Comma-Separated Values) is one of the most popular formats for exchanging tabular data. In PHP, working with CSV is implemented natively, without installing additional libraries. In this article, we will cover all aspects: from basic reading to advanced processing of large files.



Core Functions for Working with CSV



PHP provides two key functions for working with CSV:

  • fgetcsv() — reading a CSV line from a file
  • fputcsv() — writing a line in CSV format


Additionally, standard file handling functions are used: fopen(), fclose(), file().



Reading a CSV File in PHP



The simplest way to read a CSV is to use a while loop with fgetcsv():



<?php$filename = 'data.csv';

if (($handle = fopen($filename, 'r')) !== false) { // Read headers (first row) $headers = fgetcsv($handle, 1000, ','); // Read the remaining rows while (($row = fgetcsv($handle, 1000, ',')) !== false) { echo "Name: " . $row[0] . ", Email: " . $row[1] . "<br>"; } fclose($handle);}?>


Parameters of fgetcsv():

  • handle — file handle
  • length — maximum line length (default 0 — no limit)
  • separator — field delimiter (default comma)
  • enclosure — quote character (default double quote)
  • escape — escape character (default backslash)


Reading CSV with Custom Delimiters



Not all CSVs use a comma. Semicolons (;) or tabs are also common:



<?php$handle = fopen('data.tsv', 'r');while (($row = fgetcsv($handle, 1000, "\\t")) !== false) {    print_r($row);}fclose($handle);?>


Writing Data to CSV



The fputcsv() function automatically handles escaping and quoting:



<?php$data = [    ['Ivan', 'ivan@example.com', 25],    ['Maria', 'maria@example.com', 30],    ['Petr', 'petr@example.com', 28]];

$handle = fopen('users.csv', 'w');

// Write headersfputcsv($handle, ['Name', 'Email', 'Age']);

// Write dataforeach ($data as $row) { fputcsv($handle, $row);}

fclose($handle);echo "CSV file successfully created!";?>


Parameters of fputcsv():

  • handle — file handle
  • fields — array of fields to write
  • separator — field delimiter
  • enclosure — quote character
  • escape — escape character


Exporting Data to CSV for Download



Often you need to generate a CSV and serve it to the user for download:



<?php$data = [    ['Product', 'Price', 'Quantity'],    ['Laptop', 75000, 10],    ['Mouse', 1500, 50],    ['Keyboard', 3500, 30]];

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

$output = fopen('php://output', 'w');// Add BOM for correct Cyrillic display in Excelfprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

foreach ($data as $row) { fputcsv($output, $row);}

fclose($output);exit;?>


Processing Large CSV Files



When working with large files (hundreds of thousands of rows), it is important to avoid loading the entire file into memory. Use streaming processing:



<?phpfunction processLargeCSV($filename, $batchSize = 1000) {    $handle = fopen($filename,                    

Recommendations