What are the steps involved in creating a CSV file in PHP and prompting the user to save it locally?
To create a CSV file in PHP and prompt the user to save it locally, you can use the following steps: 1. Create an array with the data you want to export to the CSV file. 2. Open a file handle using fopen() function with 'w' mode to write to the file. 3. Loop through the data array and write each row to the file in CSV format using fputcsv() function. 4. Close the file handle. 5. Finally, use header() function to set the Content-Disposition to 'attachment' and the filename to prompt the user to save the file locally.
<?php
// Data to be exported to CSV
$data = array(
array('Name', 'Age', 'Email'),
array('John Doe', 30, 'john@example.com'),
array('Jane Smith', 25, 'jane@example.com')
);
// Open file handle
$fp = fopen('export.csv', 'w');
// Write data to CSV file
foreach ($data as $row) {
fputcsv($fp, $row);
}
// Close file handle
fclose($fp);
// Prompt user to save the file
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
?>
Keywords
Related Questions
- How can the UPDATE SQL command be effectively utilized to overwrite existing data in a MySQL database using PHP?
- In the context of the forum thread, what suggestions were given to the user experiencing the issue of "Undefined variable: id"?
- What are the advantages of using a 2-step check for email validation in PHP?