Categories
PHP

Reading and Writing CSV Files

CSV is a file format and stands for “comma-separated values”. In this tutorial, we use the fgetcsv() function to read a CSV file and fputcsv() function to write CSV records into a file.

This tutorial covers the following topics:

Reading CSV Files

This tutorial shows how to extract the values from a CSV file into a multidimensional associative array using fopen() and fgetcsv() functions. The fgetcsv() function works similar to the fgets() but it converts the line into an array, separating the contents at a comma (or any other character). Visit Parse the CSV String tutorial if you want to parse a string instead of a CSV file.

Example: Reading CSV File

The sample file contains the following data as comma-separated values:

a,b,c
d,e,f
g,h,i
  1. Next, create a PHP script and use the fopen() function to open file.csv in read mode.
  2. Create an empty array, $lines, to store the values that will be extracted from the file.
  3. Create the while loop and use !feof($fp) as the condition.
  4. Use the fgetcsv() function to extract the lines from the file as an array, and assign them to $lines array:
<?php
 $fp = fopen('file.csv', 'r');
 $lines = array();
 while (!feof($fp)) {
  $lines[] = fgetcsv($fp);
 }
 fclose($fp);

 echo '<pre>';
 print_r($lines);

The preceding code prints the following data on the browser:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
            [0] => d
            [1] => e
            [2] => f
        )

    [2] => Array
        (
            [0] => g
            [1] => h
            [2] => i
        )
)

Example: Converting CSV File into HTML Table

<style>td {border: 1px solid black;padding:5px}</style>
<table>
<?php
 $fp = fopen('file.csv', 'r');
 while (!feof($fp)) {
  $row = fgetcsv($fp);
  echo '<tr>';
  foreach ($row as $cell)
   echo "<td>$cell</td>";
  echo "</tr>\n";
 }
 fclose($fp); 
?>
<table>

The code reads in a CSV file and outputs it as an HTML table, it displays the following output on the browser:

Example: Reading from a tab delimited file

By default, the fgetcsv() function uses the comma as the field delimiter. To read a tab-separated file, specify the “\t” as the delimiter in the third parameter for fgetcsv():

<?php
 $fp = fopen('file.csv', 'r');
 $lines = array();
 while (!feof($fp)) {
  $lines[] = fgetcsv($fp, null, "\t");
 }
 fclose($fp);

 echo '<pre>';
 print_r($lines);

fgetcsv()

<?php
 //Syntax
 fgetcsv(
    resource $stream,
    ?int $length = null,
    string $separator = ",",
    string $enclosure = "\"",
    string $escape = "\\"
 ): array|false

The fgetcsv function takes the following parameters:

  • $stream: The file pointer.
  • $length: (optional) Define the maximum length of a line in the CSV file you want to extract the remaining data will get truncated.
  • $separator: (optional) The field separator (delimiter), the default value is the comma.
  • $enclosure: (optional) Set the field enclosure character.
  • $escape: (optional) Set the escape character. The default is a backslash.

Writing to a CSV File

For writing CSV files, PHP offers a sister function, fputcsv(). You provide a file pointer and an array of values, and PHP does the rest, including escaping special characters.

<?php
  $data = array(
    array('April 2022', '19,720,597', '1,310,181'),
    array('January 2022', '18,455,683', '1,317,871'),
    array('December 2022', '17,826,404', '1,318,739')
  );
  if ($fp = fopen('file.csv', 'w')) {
    foreach ($data as $line) {
      fputcsv($fp, $line);
    }
    fclose($fp);
    echo 'CSV written.';
  } else {
    echo 'Cannot open file.';
  }

This code creates the file file.csv with the following contents:

"April 2022","19,720,597","1,310,181"
"January 2022","18,455,683","1,317,871"
"December 2022","17,826,404","1,318,739"

Example: Writing to a tab-delimited file

By default, the fputcsv() function uses the comma as the field delimiter. To write a tab-separated file, specify the “\t” as the delimiter in the third parameter:

<?php
  $data = array(
    array('April 2022', '19,720,597', '1,310,181'),
    array('January 2022', '18,455,683', '1,317,871'),
    array('December 2022', '17,826,404', '1,318,739')
  );
  if ($fp = fopen('file.csv', 'w')) {
    foreach ($data as $line) {
      fputcsv($fp, $line, "\t");
    }
    fclose($fp);
    echo 'CSV written.';
  } else {
    echo 'Cannot open file.';
  }

This code creates the file file.csv with the following contents:

"April 2022"	19,720,597	1,310,181
"January 2022"	18,455,683	1,317,871
"December 2022"	17,826,404	1,318,739

fputcsv

<?php
fputcsv(
    resource $stream,
    array $fields,
    string $separator = ",",
    string $enclosure = "\"",
    string $escape = "\\",
    string $eol = "\n"
): int|false

The fputcsv function returns the length of the written string or false on failure, it takes the following parameters:

  • $stream: The file pointer opened by fopen().
  • $fields: An array of strings.
  • $separator: (optional) Field delimiter, the default value is a comma.
  • $enclosure: (optional) Filed enclosure, the default value is a double quotation mark.
  • $escape: (optional) Define the escape character.
  • $eol: (optional) Define a custom End of Line sequence.

Working with Files in PHP: