305 of 410 menu

The fgetcsv Function

The fgetcsv function reads a line from a file and parses it into fields in CSV format. The first parameter of the function is a pointer to an open file, the second is the maximum line length, the third is the field separator (comma by default), the fourth is the enclosure character (double quotes by default), and the fifth is the escape character.

Syntax

fgetcsv( resource $handle, int $length = 0, string $separator = ",", string $enclosure = "\"", string $escape = "\" );

Example

Let's read a CSV file line by line and output the contents:

<?php $file = fopen('data.csv', 'r'); while (($row = fgetcsv($file)) !== false) { print_r($row); } fclose($file); ?>

The result of executing the code for a file with the contents "a,b,c":

['a', 'b', 'c']

Example

Reading CSV with specifying the maximum line length and a custom separator:

<?php $file = fopen('data.csv', 'r'); while (($row = fgetcsv($file, 1000, ';')) !== false) { print_r($row); } fclose($file); ?>

The result of executing the code for a file with the contents "a;b;c":

['a', 'b', 'c']

Example

Reading CSV with quotes and escaping:

<?php $file = fopen('data.csv', 'r'); while (($row = fgetcsv($file, 0, ',', '"', '\')) !== false) { print_r($row); } fclose($file); ?>

The result of executing the code for a file with the contents '"a,b",c,"d\"e"':

['a,b', 'c', 'd"e']

See Also

  • the fputcsv function,
    which writes data to CSV
  • the fgets function,
    which reads a line from a file
byenru