I have a CSV file called employee_data.csv. It contains employee records formatted like so:
JANE WILLIAMS,6/8/1998,55846874E,4323
PETER JONES,15/01/1982,56897547Q,1234
JAMES O'BRIEN,09/05/2001,25689514W,3432
I want to delete a selected row within the csv file. To achieve this, I will simply copy the 2 rows within the csv file that I do not want to delete to a new_employee_data.csv file and delete the old one.
<?php
$dataSrc = "persistence/employee_data.csv";
$dataDest = "persistence/new_employee_data.csv";
$dataFile = fopen($dataSrc, "r") or die("Unable to open file!");
$outFile = fopen($dataDest, "w") or die("Unable to open file!");
$i=0; //index for the array
while(!feof($dataFile)) {
$csv = fgetcsv($dataFile); //read a line from the CSV file
//$csv = [ANE WILLIAMS,6/8/1998,55846874E,4323];
//add check to remove row
print_r($csv);
if($csv[2] == '55846874E') continue; //skip to next itteration
fputcsv($outFile, $csv);
}
fclose($dataFile);
fclose($outFile);
?>
The code above takes the contents of $dataFile and writes it to $outFile line by line, if the 3rd column = '55846874E' it will skip writing that line. The csv array contains the rows within the employee_data.csv file.
The elements in the $csv array are as follows.
Array ( [0] => JANE WILLIAMS [1] => 6/8/1998 [2] => 55846874E [3] => 4321 )
Array ( [0] => PETER JONES [1] => 15/01/1982 [2] => 56897547Q [3] => 1234 )
Array ( [0] => JAMES O'BRIEN [1] => 09/05/2001 [2] => 25689514W [3] => 8475 )
It removes the first row of the file - JANE WILLIAMS,6/8/1998,55846874E,4323
Now in the new_employee_data.csv is the two undeleted records.
"PETER JONES",15/01/1982,56897547Q,1234
"JAMES O'BRIEN",09/05/2001,25689514W,8475
This is exactly what I want it to do however I received this warning when I run it in the browser:
fputcsv() expects parameter 2 to be array, boolean given in line 25
It's having a problem with fputcsv($outFile, $csv); and I've no idea why, any suggestions of how to fix this?
fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.Which tells me that it most likely reached the end of the file