how to delete line number 3 or any line of my csv file ?????????????????


like
test.csv

1.jhon
2.sarah
3.ricky //delete this row of csv
4.martin

Member Avatar

diafol

Depends, do you want the numbers to follow, or will a simple delete do?

You can:

1. get the contents of the file via file_get_contents().
2. split the contents into an array with explode(), use "\n" as a delimiter.
3. delete the 3rd entry ('2') with array_splice().
4. implode the array using "\n" for the delimiter.
5. save the changes with file_put_contents().

If any of these functions are unfamiliar, look them up in the php.net manual. If stuck, come back, I've got the code, but show your workings first.

my csv file is so big it has more than 1 Lac lines.
so i cant offered to delete each line in end of program,,,,i want delete each line after display or process
(display line,then delete this line=>display line,then delete this line..............)

Try this.

<?php
$cnt = 0;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($csvadata = fgetcsv($handle, 0, ",")) !== FALSE) {      
	   $data[$cnt++] = $csvadata;
    }
    fclose($handle);
	unset($data[2]);
}
$fp = fopen('test.csv', 'w');
foreach ($data as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);
?>