📂 PHP File Handling
Estimated reading: 3 minutes 362 views

PHP Handle CSV File – Read and Write CSV Data in PHP Easily

Learn how to read, write, and process CSV files in PHP using built-in functions like fgetcsv() and fputcsv() for structured data handling.


Introduction – Why Work with CSV Files in PHP?

CSV (Comma-Separated Values) files are a widely used format for data export/import, especially between databases, spreadsheets, and applications. PHP provides native functions to easily read and write CSV files, making it ideal for building reporting tools, import wizards, or database migration utilities.

In this guide, you’ll learn:

  • How to read CSV files row-by-row using fgetcsv()
  • How to write CSV data with fputcsv()
  • How to handle special characters and delimiters
  • Real-world use cases and best practices

1. Reading a CSV File with fgetcsv()

$handle = fopen("data.csv", "r");

while (($row = fgetcsv($handle)) !== false) {
    print_r($row);
}

fclose($handle);

fgetcsv() reads one row at a time and returns it as an array.
Automatically parses CSV fields using commas as default delimiters.


2. CSV File Format Example

data.csv

Name,Email,Age
Alice,alice@example.com,25
Bob,bob@example.com,30

Output from fgetcsv():

Array ( [0] => Name [1] => Email [2] => Age )
Array ( [0] => Alice [1] => alice@example.com [2] => 25 )
Array ( [0] => Bob [1] => bob@example.com [2] => 30 )

Each line is returned as an indexed array.


3. Writing to a CSV File with fputcsv()

$data = [
    ["Name", "Email", "Age"],
    ["Alice", "alice@example.com", 25],
    ["Bob", "bob@example.com", 30]
];

$handle = fopen("output.csv", "w");

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

fclose($handle);

fputcsv() writes an array as a single CSV row.
Automatically adds commas and wraps fields if needed.


4. Custom Delimiters and Enclosures

fputcsv($handle, $row, ";", '"');

Customize field separator (;) and enclosure (") for compatibility.
Useful when working with regional or third-party formats.


5. Appending to a CSV File

$handle = fopen("log.csv", "a");
fputcsv($handle, ["Dave", "dave@example.com", 28]);
fclose($handle);

Open file with "a" mode to append new rows.
Preserves existing CSV data.


6. Reading CSV into Associative Arrays

$handle = fopen("data.csv", "r");
$headers = fgetcsv($handle);

while (($row = fgetcsv($handle)) !== false) {
    $assoc[] = array_combine($headers, $row);
}

fclose($handle);
print_r($assoc);

Combine headers with values to create associative arrays.
Easier to access values using column names like $row["Email"].


Best Practices

  • Always use fclose() to release file resources
  • Validate CSV format and encoding before processing
  • Use array_combine() for structured associative output
  • Escape special characters when outputting to avoid CSV corruption
  • Avoid loading large CSV files into memory — use line-by-line reading

Summary – Recap & Next Steps

Handling CSV files in PHP is simple and efficient using fgetcsv() and fputcsv(). It’s a reliable solution for data import/export, reporting, and integration with Excel or spreadsheet tools.

Key Takeaways:

  • Use fgetcsv() to read CSV rows line-by-line
  • Use fputcsv() to write arrays into structured CSV files
  • Support custom delimiters and field enclosures
  • Prefer associative arrays for better readability

Real-World Use Cases:
Data exports, CRM imports, order records, logs, user reports, analytics, spreadsheet tools.


Frequently Asked Questions (FAQs)

How to skip the header row in a CSV file?
Use fgetcsv() once before entering the loop to skip headers.

How to change the delimiter in a CSV file?
Pass a custom delimiter to fgetcsv() or fputcsv() like: fgetcsv($handle, 0, ";").

Can I read a CSV file into an associative array?
Yes, use array_combine() with the first row as headers.

Does fputcsv() overwrite the file?
Yes, in "w" mode. Use "a" mode to append.

Is CSV file handling available by default in PHP?
Yes, no external libraries needed.


Share Now :
Share

📊 PHP Handle CSV File

Or Copy Link

CONTENTS
Scroll to Top