PHP: How to read and write to a CSV file

Updated: January 11, 2024 By: Guest Contributor Post a comment

Overview

Handling CSV (Comma Separated Values) files is a common data exchange format used in various programming tasks. PHP provides built-in functions to read from and write to CSV files, making it easy to integrate CSV data management into web applications.

Opening a CSV File

To get started with PHP’s CSV handling, one must first understand how to open and close a CSV file. The fopen() function is used to open a file, and fclose() function is used to close it. Here’s an example:

<?php
$file = fopen("data.csv", "r");
// Perform file operations
fclose($file);
?>

Reading from a CSV File

PHP’s fgetcsv() function can be used to read data from a CSV file. Consider the following example:

<?php
$file = fopen("data.csv", "r");
while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
   // Process each line of data here
}
fclose($file);
?>

This will read up to 1000 characters on each line until the end of the file is reached. The fgetcsv() function also automatically handles different CSV formats, including those enclosed by quotes or with escaped characters.

Writing to a CSV File

To write to a CSV file, PHP’s fputcsv() function comes in handy. Below is how you can use it:

<?php
$list = array (
    array('Alice', 'Doe', '[email protected]'),
    array('Bob', 'Smith', '[email protected]')
);

$file = fopen('data.csv', 'w');
foreach ($list as $fields) {
    fputcsv($file, $fields);
}
fclose($file);
?>

This code snippet creates or overwrites the ‘data.csv’ file, then writes multiple lines of data in CSV format.

Parsing CSV Data with Associative Arrays

A more advanced technique involves associating CSV data with key-value pairs. To do this:

<?php
$header = NULL;
$data = array();
$file = fopen('data.csv', 'r');
while ($row = fgetcsv($file)) {
    if (!$header)
        $header = $row;
    else
        $data[] = array_combine($header, $row);
}
fclose($file);
var_dump($data);
?>

This code reads the first row as headers and each subsequent row as data associated with those headers, resulting in a data array of associative arrays.

Handling Different Delimiters and Enclosures

CSV files may not always use commas to separate values. PHP’s fgetcsv() and fputcsv() functions can handle different delimiters and enclosure characters. Here’s how:

<?php
// Reading from a CSV file with semi-colon separator
$file = fopen('data.csv', 'r');
while (($data = fgetcsv($file, 1000, ';')) !== FALSE) {
    // Process each line of data here
}
fclose($file);

// Writing to a CSV file with pipe delimiter
$list = array(
    array('Alice', 'Doe', '[email protected]'),
    array('Bob', 'Smith', '[email protected]')
);
$file = fopen('data.csv', 'w');
foreach($list as $fields) {
    fputcsv($file, $fields, '|');
}
fclose($file);
?>

Changing the third parameter in fgetcsv() reads files with different delimiters, and adding a fourth parameter to fputcsv() writes files with a delimiter other than a comma.

Conclusion

PHP offers a robust set of functions for working with CSV files, simplifying tasks such as data reporting, exporting, and migrating complex datasets. By mastering these functions, developers can streamline data manipulation and enhance application functionality with ease.