Reputation: 115
I have this PHP code that selects data from a database and creates a CSV file.
Its working fine, but how can i force download of the CSV file once it has finished being created?
I have added the headers at the top of the page but its not download the file
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=calls.csv');
$filename = $SettingsCustomer["company"].'-CallsTariff'.'-'.date("YmdHis");
// create a file pointer connected to the output stream
$output = fopen($_SERVER["DOCUMENT_ROOT"].'/file_dump/price_tariffs/'.$filename.'.csv', 'w');
// output the column headings
fputcsv($output, array('Number', 'Description', 'Per Minute Cost'));
// loop over the rows, outputting them
$cost=0;
$sql="SELECT * from call_costs where sequence < '50' ";
$rs=mysql_query($sql,$conn);
while($result = mysql_fetch_array($rs)) {
//check for custom costs
$sql2="SELECT * from call_costs_custom where parent = '".$result["sequence"]."' AND customer_seq = '".$SettingsCustomer["sequence"]."' ";
$rs2=mysql_query($sql2,$conn);
if(mysql_num_rows($rs2) > 0) {
$result2=mysql_fetch_array($rs);
$cost = $result2["cost"];
} else {
$cost = $result["retail"];
}
fputcsv($output, array($result["number"], $result["description"], $cost));
}
Upvotes: 3
Views: 9953
Reputation: 233
Charlie, this is a sample way to create and force download to csv file. Try to implement this in your code:
<?php
$filename = 'test';
$filepath = $_SERVER["DOCUMENT_ROOT"] . $filename.'.csv';
$output = fopen($filepath, 'w+');
fputcsv($output, array("Number", "Description", "test"));
fputcsv($output, array("100", "testDescription", "10"));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
header('Content-Length: ' . filesize($filepath));
echo readfile($filepath);
Upvotes: 4
Reputation: 792
Well you need that at your end...
$file = '/file_dump/price_tariffs/'.$filename.'.csv';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
You can remove the get_content_file
Upvotes: 0
Reputation: 792
Please search the next time better. Thats everytime the same answer
header('Content-Type: application/octet-stream');
text/csv is a display able content-type
Upvotes: 0