How can PHP scripts be optimized to ensure that CSV output is formatted correctly and efficiently?
To optimize PHP scripts for correctly and efficiently formatting CSV output, it is important to properly handle special characters, enclose fields within quotes if necessary, and use fputcsv() function for writing CSV data. Additionally, setting the appropriate headers for CSV download can improve the user experience.
<?php
// Sample data array
$data = [
['Name', 'Age', 'Country'],
['John Doe', 30, 'USA'],
['Jane Smith', 25, 'Canada'],
['Ahmed Ali', 35, 'Pakistan']
];
// Set headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
// Open output stream
$fp = fopen('php://output', 'w');
// Iterate over data and write to CSV
foreach ($data as $row) {
fputcsv($fp, $row);
}
// Close the output stream
fclose($fp);
?>