PHP - Reading CSV Files

Introduction

To read CSV files, you can usefgetcsv().

This function reads a line of CSV-formatted data from an open file starting from the position of the file pointer.

Puts the data it finds into an array, with one field value per array element.

To call the fgetcsv() function, pass it the file handle of an open file.

You can also optionally specify:

  • The maximum number of characters to read. You can leave this value out, or use 0, in which case PHP reads as many characters as necessary to read the whole line.
  • The delimiter to separate each data value. The default is the comma (,).
  • The character to enclose string values. The default is the double quote (" ).
  • The character to escape special characters. The default is the backslash (\).

fgetcsv() returns false if there was a problem reading the line, or if the end of the file has been reached.

The following code snippet shows how you might retrieve three lines of data from a file in CSV format:

/*
 people.csv contains:
  "A" ,"Json" ,5
  "B" ,"Java" ,7
  "C" ,"Jason" ,2
*/

$handle = fopen(" people.csv" ," r" );
while ($record = fgetcsv($handle, 1000)) {
 echo " Name: {$record[0]} {$record[1]}, Age: {$record[2]} \n" ;
}

fclose($handle);