The SplFileObject class provides an object oriented interface for a file.
$file="upload_file.csv"; //file to parse
Steps:
1) Create SplFileObject class object to the csv file.
$srcFile = new SplFileObject($file);
2)Now loop till end of file found.
while (!$srcFile->eof()) //eof() returns true if file is at EOF else false.
{
$data=$file->fgetcsv(); // gets a line from the csv file and returns an fields array.
}
Similarly for writing csv :
$arr = array (
array('1', '2', '3', '4'),
array('5', '6', '7')
);
$file = new SplFileObject('file.csv', 'w');
foreach ($arr as $fields) {
$file->fputcsv($fields); //this method works only in php 5.4 and above
}
0 Comment(s)