The fgetcsv()
function reads a line from the file pointer and parses the CSV field.
Similar to fgets()
, the difference is that fgetcsv()
parses the read lines and finds fields in CSV format, and then returns an array containing these fields.
FALSE is returned when fgetcsv()
error occurs, including when the file ends.
Note: Since PHP 4.3.5, the operation of fgetcsv()
is binary safe.
<?php $file = fopen ( "contacts.csv" , "r" ) ; print_r ( fgetcsv ( $file ) ) ; fclose ( $file ) ; ?>
CSV file:
George , John , Thomas , USA James , Adrew , Martin , USA
The output is similar:
Array ( [0] => George [1] => John [2] => Thomas [3] => USA )
<?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
The output is similar:
Array ( [0] => George [1] => John [2] => Thomas [3] => USA Array ( [0] => James [1] => Adrew [2] => Martin [3] => USA )
fgetcsv ( file , length , separator , enclosure )
parameter | describe |
---|---|
file | Required. Specify documents to be inspected. |
length |
Optional. The maximum length of the specified line. Must be greater than the longest line in the CVS file. This parameter is optional in PHP 5. It is required before PHP 5. If this parameter is ignored (set to 0 in PHP 5.0.4 and later), then there is no limit on the length, but it may affect execution efficiency. |
separator | Optional. Sets the field delimiter (only one character is allowed), the default value is comma. |
enclosure |
Optional. Sets the field surround character (only one character is allowed), with the default value being double quotes. This parameter was added in PHP 4.3.0. |