How can the fgetcsv and fputcsv functions in PHP be utilized to efficiently work with CSV files?
To efficiently work with CSV files in PHP, you can use the fgetcsv function to read data from a CSV file line by line and the fputcsv function to write data to a CSV file in a formatted manner. These functions handle parsing and formatting of CSV data, making it easier to work with CSV files without having to manually handle delimiters and escaping characters.
// Reading data from a CSV file using fgetcsv
$csvFile = fopen('data.csv', 'r');
while (($data = fgetcsv($csvFile)) !== false) {
// Process each row of data
print_r($data);
}
fclose($csvFile);
// Writing data to a CSV file using fputcsv
$csvFile = fopen('output.csv', 'w');
$data = ['John Doe', 'john.doe@example.com', '555-1234'];
fputcsv($csvFile, $data);
fclose($csvFile);