Skip to content
PHP Logo

How can a script be used to remove an entry from a CSV file in PHP?

To remove an entry from a CSV file in PHP, you can read the contents of the CSV file, filter out the entry you want to remove, and then rewrite the updated contents back to the CSV file.

php
<?php
// Open the CSV file for reading and writing
$file = fopen('data.csv', 'r+');

// Read the contents of the CSV file into an array
$rows = [];
while (($data = fgetcsv($file)) !== false) {
    $rows[] = $data;
}

// Filter out the entry you want to remove
$entryToRemove = ['John', 'Doe'];
$rows = array_filter($rows, function($row) use ($entryToRemove) {
    return $row !== $entryToRemove;
});

// Rewind the file pointer and truncate the file
ftruncate($file, 0);
rewind($file);

// Write the updated contents back to the CSV file
foreach ($rows as $row) {
    fputcsv($file, $row);
}

// Close the file
fclose($file);
?>