Naveen
Naveen

Reputation: 41

Delete current iterating row from CSV file in PHP

I want to delete current iterating row from CSV file, Suppose I have 5 rows (1,2,3,4,5) into my CSV file, I opened my file while iterating the rows one by one using foreach, when it comes to 3rd row then 3rd row should be deleted from CSV file and other 1,2,4,5 rows will be same while same iterration. I don't want to use like Skip the 3rd iterration and save it into another file, not like rename file name. So, Please anyone can help me how to do this in PHP?

Suppose, like SQL command to delete current row, is there anything in PHP?

Thanks.

Upvotes: 3

Views: 1795

Answers (1)

S.Gartmeier
S.Gartmeier

Reputation: 491

You will need to have permissions to write the file. If you remove a row, you will have to save the file. As you do not want to have any empty rows as well, you need to read the whole file.

I suggest to get the file content, and split it into a array by lines. With the explode function you can split the content by the line break, most likely "\n". So an array wich will contain each line of the csv file will be existing. Now you can simply remove the line from the array and create a string out of it, before saveing the changed content back to the csv file.

// get csv content into string variable
$csvContent = file_get_contents(__DIR__ . "/yourfile.csv");
// create array out of csv, limited by PHP_EOL wich determines the systems line break
// this means, every line in the csv file will be represended by an array key and its value
$csvArray = explode(PHP_EOL, $csvContent);

// unset the 3th csv line. 
unset($csvArray[2]); // keep in mind array starts at 0, so third line is array key 2 

// from here on you can manipulate the array $csvArray as you like. 
// add lines, remove lines or just use the given content for future operations. 
// you can also iterate over the array with: foreach ($csvArray as $line => $value) {}

// create string out of modified csv array
$csvContent = implode(PHP_EOL, $csvArray);
// save result back into the csv file
file_put_contents( __DIR__ . "/yourfile.csv", $csvContent);

Check implode/explode php function docs:

http://php.net/manual/en/function.implode.php

http://php.net/manual/en/function.explode.php

Upvotes: 4

Related Questions