I am trying to create a csv file upon a button click. The problem i have is that the file wont download, it just echos out the content.
This is my code
class csv_writer {
public $dataArray;
public $filename;
public $csvHeader;
public function create_csv() {
/**
*
* Creates the CSV and make it ready for download
*/
$fp = fopen('php://output', 'w');
fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF) );
fputcsv($fp, $this->csvHeader, ';',' ');
foreach ( $this->dataArray as $ferow ) {
fputcsv($fp, $ferow,';');
}
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$this->filename.'.csv"');
fclose($fp);} }
This is how i call the class:
$csv = new csv_writer();
$csv->dataArray = array( 'value1', 'value2' );
$csv->filename = 'test';
$csv->csvHeader = array( 'value1', 'value2' );
$csv->create_csv();
I have tried every other exmaple here on stack, but with no luck! Hopefully there is a bright mind out there that can help me out!
You haven't produced any content, only the filename.
Here follows a codesnippet I wrote some time ago.
It is up to you to create the output.
In short: FIRST set the headers (including the filenamesuggestion).
Then the content.
$filenameSuggestion = "database_export_".date("d")."-".date("F")."-".date("Y").".sql";
header("Content-Disposition: attachment; filename=\"".$filenameSuggestion."\"");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
// Create content HERE, so you need to echo something or create output another way
// .....
exit;
I hope this helps you going.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.