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

Dani AI

Generated

For large CSVs, avoid loading the whole file into memory. Text files cannot delete bytes in the middle in-place, so the common pattern is: stream-read the source, write every row except the one you want to remove to a temporary file, then atomically replace the original. This is O(1) memory and scales to hundreds of thousands of lines.

<?php
$source = 'test.csv';
$tmp    = $source . '.tmp';
$skip   = 3; // 1-based line number to remove

$in  = fopen($source, 'rb') or exit('Cannot open source');
$out = fopen($tmp, 'wb')    or exit('Cannot open temp');

// optional locking if other processes may read/write the file
flock($in, LOCK_SH);
flock($out, LOCK_EX);

$line = 0;
while (($row = fgetcsv($in)) !== false) {
    $line++;
    if ($line === $skip) { continue; }
    fputcsv($out, $row);
}

fflush($out);
flock($in, LOCK_UN);
flock($out, LOCK_UN);
fclose($in);
fclose($out);

// replace original (same filesystem for atomic rename)
if (!rename($tmp, $source)) { unlink($tmp); exit('Replace failed'); }

Notes:

  • If the numbers (1., 2., 3.) are part of the data, they will not be auto-renumbered; renumber after the rewrite if needed.
  • fgetcsv handles line endings and quoted fields; do not split on "\n" yourself. See fgetcsv and fputcsv.
  • Use file locks when concurrency is possible: flock.
  • Replace safely with rename; on Windows, ensure no other process holds the file open.

Recommended Answers

All 3 Replies

Member Avatar for Member #120589

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);
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.