phpcsvfopenfgetcsv

Remove Line From CSV File


I have .csv file with 4 columns. What's the easiest way to remove a line identical with the id of the first column? Here's where I got stuck:

if($_GET['id']) {
    $id = $_GET['id'];
    $file_handle = fopen("testimonials.csv", "rw");

    while (!feof($file_handle) ) {
        $line_of_text = fgetcsv($file_handle, 1024);    
        if ($id == $line_of_text[0]) {
            // remove row
        }
    }
    fclose($file_handle);
}

Unfortunately, databases were not a choice.


Solution

  • $id = $_GET['id'];
    if($id) {
        $file_handle = fopen("testimonials.csv", "w+");
        $myCsv = array();
        while (!feof($file_handle) ) {
            $line_of_text = fgetcsv($file_handle, 1024);    
            if ($id != $line_of_text[0]) {
                fputcsv($file_handle, $line_of_text);
            }
        }
        fclose($file_handle);
    }