PHP fgetcsv() function

Definition and Usage

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

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

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

Anmerkung: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 in the CVS file.

In PHP 5, this parameter is optional. Before PHP 5, it is required.

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

separator Optional. Setzen Sie das Feldtrennzeichen (es darf nur ein Zeichen sein), Standardwert ist Komma.
enclosure

Optional. Setzen Sie das Feldumrandungssymbol (es darf nur ein Zeichen sein), Standardwert sind Anführungszeichen.

Dieser Parameter wurde in PHP 4.3.0 hinzugefügt.

Hinweise und Anmerkungen

Anmerkung:Leere Zeilen in CSV-Dateien werden als Array mit einem einzelnen null-Feld zurückgegeben und werden nicht als Fehler behandelt.

Anmerkung:Diese Funktion ist an die Regionaleinstellungen angepasst. Zum Beispiel kann es bei einer Einstellung von LANG auf en_US.UTF-8 zu Lesefehlern bei Dateien mit Einzellangzeichen编码 kommen.

Anmerkung:Wenn PHP bei der Leseoperation Dateien mit Macintosh-Dateiendezeichen nicht erkennen kann, kann die Laufzeiteinstellung auto_detect_line_endings aktiviert werden.

Beispiel

Beispiel 1

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

CSV-Datei:

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

Ausgabe ähnlich:

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

Beispiel 2

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

CSV-Datei:

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

Ausgabe ähnlich:

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