Sling Academy
Home/PHP/PHP: How to read and write to a CSV file

PHP: How to read and write to a CSV file

Last updated: January 11, 2024

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.

Next Article: PHP: How to get file name/extensions from a path

Previous Article: PHP: How to download a large file from the internet

Series: PHP System & FIle I/O Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array