PHP fgetcsv() Function
The PHP fgetcsv() function gets line from file pointer and parse for CSV fields. It is similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.
Syntax
fgetcsv(stream, length, separator, enclosure, escape)
Parameters
stream |
Required. Specify a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen(). |
length |
|
separator |
Optional. Specify the field delimiter (one single-byte character only). Default is comma ( , ) |
enclosure |
Optional. Specify the field enclosure character (one single-byte character only). Default is ". |
escape |
Optional. Specify the field escape character (at most one single-byte character). Default is backslash (\). An empty string ("") disables the proprietary escape mechanism. |
Return Value
Returns an indexed array containing the fields read.
Example: parsing first line of the CSV file
Lets assume that we have a CSV file called data.csv. This file contains following content:
The example below shows how to use the fgetcsv() function to parse first line of the file.
<?php //opening the CSV file in read mode $fp = fopen("data.csv","r"); //parsing the first line of the //the CSV file $csvArr = fgetcsv($fp); //displaying the result array print_r($csvArr); //closing the file fclose($fp); ?>
The output of the above code will be:
Array ( [0] => EmpID [1] => Name [2] => Age [3] => Salary )
Example: parsing the entire contents of a CSV file
The below example can be used to parse the whole content of the CSV file into arrays.
<?php //opening the CSV file in read mode $fp = fopen("data.csv","r"); while(!feof($fp)){ //parsing the CSV file line by line $csvArr = fgetcsv($fp); //displaying the result array print_r($csvArr); } //closing the file fclose($fp); ?>
The output of the above code will be:
Array ( [0] => EmpID [1] => Name [2] => Age [3] => Salary ) Array ( [0] => 1 [1] => John [2] => 25 [3] => 3000 ) Array ( [0] => 2 [1] => Marry [2] => 24 [3] => 2750 ) Array ( [0] => 3 [1] => Jo [2] => 27 [3] => 2800 ) Array ( [0] => 4 [1] => Kim [2] => 30 [3] => 3100 ) Array ( [0] => 5 [1] => Ramesh [2] => 28 [3] => 3000 )
❮ PHP Filesystem Reference