The fgetcsv() function parses a line from an open file to check for CSV fields. It returns an array containing the fields read.
Syntax
fgetcsv(file_pointer, length, delimiter, enclosure, escape)
Parameters
file_pointer − A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
length − Maximum length of a line.
delimiter − Character that specifies the field separator. Default is comma ( , )
enclosure − Set the field enclosure character. Defaults as a double quotation mark.
escape − Set the escape character. Defaults as a backslash (\).
Return
The fgetcsv() function returns an array containing the fields read.
Example
Let’s say we have the following “products.csv” CSV file.
laptop, keyboard, mouse
The following is an example that displays the content of CSV, that includes the products.
<?php $file_pointer = fopen("products.csv","r"); print_r(fgetcsv($file_pointer)); fclose($file_pointer); ?>
Output
Array ( [0] => Laptop [1] => Keyboard [2] => Mouse )
Let us see another example.
We have the following “tutorials.csv” CSV file.
Java, C#, HTML5, CSS3, Bootstrap, Android
The following is an example that displays the content of CSV “tutorials.csv”.
Example
<?php $file_pointer = fopen("tutorials.csv","r"); while(! feof($file_pointer)) { print_r(fgetcsv($file_pointer)); } fclose($file_pointer); ?>
The following is the output: Java, C#, HTML5, CSS3, Bootstrap, Android
Output
Array ( [0] => Java [1] => C# [2] => HTML5 [3] => CSS3 [4] => Bootstrap [5] => Android )