How can entire rows be deleted from a CSV file using PHP?

To delete entire rows from a CSV file using PHP, you can read the CSV file, filter out the rows you want to delete, and then write the remaining rows back to the CSV file. You can achieve this by using functions like fgetcsv() to read the CSV file, array_filter() to filter out the rows to delete, and fputcsv() to write the remaining rows back to the CSV file.

$csvFile = 'example.csv';
$tempFile = 'temp.csv';

$deleteRow = 2; // Row number to delete

$handle = fopen($csvFile, 'r');
$tempHandle = fopen($tempFile, 'w');

if ($handle !== false && $tempHandle !== false) {
    while (($data = fgetcsv($handle)) !== false) {
        if ($data[0] != $deleteRow) {
            fputcsv($tempHandle, $data);
        }
    }

    fclose($handle);
    fclose($tempHandle);

    rename($tempFile, $csvFile); // Replace original file with temp file
    echo 'Row ' . $deleteRow . ' deleted successfully.';
} else {
    echo 'Error opening files.';
}