Reading
Using str_getcsv() line by line:
$spreadsheet_file = fopen($spreadsheet_path, 'r');
while (($line = fgets($spreadsheet_file)) !== false) {
$cells = str_getcsv($line);
// ...
}
Using fgetcsv(), which reads and parses a line in one call:
$row = 1;
if (($handle = fopen("test.csv", "r")) !== false) {
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c = 0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
Writing
Using fputcsv():
<?php
$list = [
['aaa', 'bbb', 'ccc', 'dddd'],
['123', '456', '789'],
['"aaa"', '"bbb"'],
];
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Andrew Dorokhov