PHP fgetcsv() function

Definition and Usage

The fgetcsv() function reads a line from the file pointer and parses CSV fields.

With fgets() Similarly, but differently, fgetcsv() parses the read line and finds CSV formatted fields, and then returns an array containing these fields.

fgetcsv() returns FALSE when an error occurs, including when the end of the file is reached.

Note:Starting from PHP 4.3.5, the operation of fgetcsv() is binary safe.

Syntax

fgetcsv(file,length,separator,enclosure)
Parameter Description
file Required. Specifies the file to be checked.
length

Optional. Specifies the maximum length of a line. It must be greater than the longest line within the CVS file.

The parameter is optional in PHP 5. It is required before PHP 5.

If the parameter is ignored (set to 0 in versions after PHP 5.0.4), there is no limit to the length, but it may affect the execution efficiency.

separator Optional. Set the field separator (only one character is allowed), the default value is comma.
enclosure

Optional. Set the field delimiter (only one character is allowed), the default value is double quotes.

This parameter was added in PHP 4.3.0.

Tips and Notes

Note:Empty lines in the CSV file will be returned as an array containing a single null field and will not be considered as an error.

Note:This function is sensitive to locale settings. For example, if LANG is set to en_US.UTF-8, reading errors will occur in files with single-byte encoding.

Note:If PHP cannot recognize the line ending character of Macintosh files when reading files, you can activate the auto_detect_line_endings runtime configuration option.

Example

Example 1

<?php
$file = fopen("contacts.csv","r");
print_r(fgetcsv($file));
fclose($file);
?>

CSV File:

George, John, Thomas, USA
James, Adrew, Martin, USA

Output similar to:

Array 
( 
[0] => George
[1] => John 
[2] => Thomas
[3] => USA
)

Example 2

<?php
$file = fopen("contacts.csv","r");
while(! feof($file))
  {
  print_r(fgetcsv($file));
  }
fclose($file);
?>

CSV File:

George, John, Thomas, USA
James, Adrew, Martin, USA

Output similar to:

Array 
( 
[0] => George
[1] => John 
[2] => Thomas
[3] => USA
Array
(
[0] => James
[1] => Adrew
[2] => Martin
[3] => USA
)