What are the best practices for reading and writing CSV files in PHP to avoid issues with formatting and data duplication?
When reading and writing CSV files in PHP, it's important to properly handle data formatting to avoid issues with data duplication and formatting errors. One way to ensure data integrity is to use the fgetcsv() function when reading CSV files, and to properly format data before writing it to a CSV file using fputcsv(). Additionally, it's recommended to sanitize input data to prevent SQL injection attacks and other security vulnerabilities.
// Read CSV file using fgetcsv()
$file = fopen('data.csv', 'r');
while (($data = fgetcsv($file)) !== false) {
// Process data here
}
fclose($file);
// Write to CSV file using fputcsv()
$data = array('John Doe', 'john.doe@example.com', '1234567890');
$file = fopen('data.csv', 'a');
fputcsv($file, $data);
fclose($file);