In PHP it is very easy to read data from CSV file using fgetcsv(), which is used to read data from a CSV file. This function reads each line of a CSV file and assign values into an array. The function returns the array of CSV fields. It returns FALSE on failure and at EOF(End Of File).
Syntax : fgetcsv(file_pointer,length,separator,enclosure,escape)
Description of function parameters :
file_pointer: File pointer, Specifies the CSV file (Required)
length: Maximum line length (in Characters). Omitting this parameter (or setting it to 0) the line length is not limited. (Optional from PHP 5)
separator: A character used as field separator (default is ','). (Optional)
enclosure: A character used for enclose values. (Optional)
escape: A character used as escape character. (Optional)
Example : Let we have a CSV file test.csv from which we want to read data.
test.csv
Roll No.,Name,Marks
1,Amit Kumar,80
2,Ashish,92
3,XYZ,68
Below is the code which reads each line from CSV file and returns an array of values for each field.
<?php
//------open CSV file---------
$file = fopen('test.csv', 'r');
//--------read data from file----------
while (($line = fgetcsv($file, 0, ",")) !== FALSE)
{
echo "<pre>";
print_r($line);
echo "</pre>";
}
fclose($file);
?>
Output :
Array
(
[0] => Roll No.
[1] => Name
[2] => Marks
)
Array
(
[0] => 1
[1] => Amit Kumar
[2] => 80
)
Array
(
[0] => 2
[1] => Ashish
[2] => 92
)
Array
(
[0] => 3
[1] => XYZ
[2] => 68
)
0 Comment(s)