PHP fgetcsv()Functions


PHP Filesystem 参考手册Complete PHP Filesystem Reference

Definition and Usage

The fgetcsv() function parses a line from an open file and validatesCSV fields.。

The fgetcsv() function stops returning a new line when it reaches the specified length or reads the end of the file (EOF), whichever comes first.

The function returns the CSV fields as an array on success, or FALSE on failure or if the end of the file (EOF) is reached.

Syntax

fgetcsv(file,length,separator,enclosure)

Parameter Description
file Required. Specifies the file to check.
length Optional. Specifies the maximum length of a line. Must be greater than the longest line in the CSV file. If this parameter is omitted (or set to 0), there is no limit on line length, but this may affect execution efficiency.

Note:This parameter was required in versions prior to PHP 5.

separator Optional. Sets the field delimiter (only one character allowed). The default is a comma ( , ).
enclosure Optional. Sets the field enclosure character (only one character allowed). The default value is a double quote ( " ).


Tips and Notes

Tip:See the fputcsv() function.


Example 1

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

CSV file:

Kai Jim, Refsnes, Stavanger, Norway
Hege, Refsnes, Stavanger, Norway

The above code will output:

Array
(
[0] => Kai Jim
[1] => Refsnes
[2] => Stavanger
[3] => Norway
)


Example 2

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

while(! feof($file))
{
print_r(fgetcsv($file));
}

fclose($file);
?>

CSV file:

Kai Jim, Refsnes, Stavanger, Norway
Hege, Refsnes, Stavanger, Norway

The above code will output:

Array
(
[0] => Kai Jim
[1] => Refsnes
[2] => Stavanger
[3] => Norway
)
Array
(
[0] => Hege
[1] => Refsnes
[2] => Stavanger
[3] => Norway
)


PHP Filesystem 参考手册Complete PHP Filesystem Reference Other Extensions