How can fopen and fgetcsv be used to delete entries that are only present once in a CSV file?
To delete entries that are only present once in a CSV file using fopen and fgetcsv, you can read the file, count the occurrences of each entry, and then rewrite the file excluding the entries that have a count of 1. This can be achieved by creating an array to store the counts of each entry, then iterating through the file to update the counts, and finally rewriting the file excluding entries with a count of 1.
<?php
$filename = 'data.csv';
// Open the CSV file for reading
$handle = fopen($filename, 'r');
// Initialize an empty array to store entry counts
$entryCounts = [];
// Read the file and update entry counts
while (($data = fgetcsv($handle)) !== false) {
$entry = $data[0];
if (!isset($entryCounts[$entry])) {
$entryCounts[$entry] = 1;
} else {
$entryCounts[$entry]++;
}
}
// Close the file
fclose($handle);
// Open the CSV file for writing
$handle = fopen($filename, 'w');
// Rewrite the file excluding entries with a count of 1
$handle = fopen($filename, 'r');
while (($data = fgetcsv($handle)) !== false) {
$entry = $data[0];
if ($entryCounts[$entry] > 1) {
fputcsv($handle, $data);
}
}
// Close the file
fclose($handle);
?>
Keywords
Related Questions
- What are some alternative solutions or libraries that can be used to create RSS feeds in PHP, especially for users of specific CMS platforms like cbportal?
- How can syntax errors, such as unexpected variables, be resolved when using functions like explode in PHP?
- What are common issues with form validation in PHP, specifically when dealing with checkbox arrays?