What is the purpose of setting the Content-type header when offering a CSV file for download in PHP?
Setting the Content-type header when offering a CSV file for download in PHP is important because it tells the browser how to handle the file being sent. By setting the Content-type to "text/csv", the browser will recognize the file as a CSV and prompt the user to download it instead of trying to display it in the browser window. This ensures that the file is downloaded correctly and can be opened in a program that supports CSV files.
<?php
// Set headers to force download the CSV file
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="example.csv"');
// Output CSV data
echo "Name, Age, City\n";
echo "John Doe, 30, New York\n";
echo "Jane Smith, 25, Los Angeles\n";
?>