fgetcsv

fgetcsv -- Get line from file pointer and parse for CSV fields

Description

array fgetcsv(int fp, int length, string [delimiter] );

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. The field delimiter is a comma, unless you specifiy another delimiter with the optional third parameter.

fp must be a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()

length must be greater than the longest line to be found in the CSV file (allowing for trailing line-end characters).

fgetcsv() returns false on error, including end of file.

NB A blank line in a CSV file will be returned as an array comprising just one single null field, and will not be treated as an error.

Example 1. Fgetcsv() example - Read and print entire contents of a CSV file

  1 
  2 $row = 1;
  3 $fp = fopen ("test.csv","r");
  4 while ($data = fgetcsv ($fp, 1000, ",")) {
  5     $num = count ($data);
  6     print "<p> $num fields in line $row: <br>";
  7     $row++;
  8     for ($c=0; $c<$num; $c++) {
  9         print $data[$c] . "<br>";
 10     }
 11 }
 12 fclose ($fp);
 13