How to create and download a csv file from php script?
To create and download a CSV file from a PHP script, you can use the following steps:
- Open a new PHP file in your text editor and set the content type to "text/csv" using the following line of code:
header('Content-Type: text/csv; charset=utf-8');
- Set the response header to specify that the file should be downloaded as an attachment with the following line of code:
header('Content-Disposition: attachment; filename=data.csv');
Create an array of data that you want to include in the CSV file. Each element in the array should represent a row in the CSV, and each element in the row should be a field in the CSV.
Use the PHP
fputcsv()
function to write the data to the file. Thefputcsv()
function takes two parameters: a file handle, and an array of data.Open a file handle for writing using the
fopen()
function, and pass the file handle and the data array to thefputcsv()
function.Close the file handle using the
fclose()
function.
Here is an example of how you can use these steps to create and download a CSV file from a PHP script:
<?php
// Set the content type to CSV
header('Content-Type: text/csv; charset=utf-8');
// Set the response header to specify that the file should be downloaded as an attachment
header('Content-Disposition: attachment; filename=data.csv');
// Create an array of data
$data = [['Name', 'Email', 'Phone'], ['John Smith', '[email protected]', '555-555-1212'], ['Jane Doe', '[email protected]', '555-555-1213']];
// Open a file handle for writing
$fp = fopen('php://output', 'w');
// Write the data to the file
foreach ($data as $row) {
fputcsv($fp, $row);
}
// Close the file handle
fclose($fp);
This script will create a CSV file with the following content:
Name,Email,Phone John Smith,[email protected],555-555-1212 Jane Doe,[email protected],555-555-1213
When the script is executed, the browser will prompt the user to download the CSV file.