๐Ÿ“‚ PHP File Handling
Estimated reading: 3 minutes 40 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ“Š PHP Handle CSV File

Or Copy Link

CONTENTS
Scroll to Top