Reputation: 6009
I have PHP script to exported record from database in to CSV file. When I click on export button, It creates a CSV file on server (current location). All data are properly being displayed in CSV file but It should not save on server, It should be downloaded in system. This question might be duplicate, but i didn't find answer.
Code for exported data in CSV file.
$monthData = mysql_query($query, $conn);
$columns_total = mysql_num_fields($monthData);
$output = "";
for ($i = 2; $i < $columns_total; $i++) {
$heading = mysql_field_name($monthData,$i);
$output .= '"'.$heading.'",';
}
$output .="\n";
while ($row = mysql_fetch_array($monthData)) {
for ($i = 2; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
$fileName = $month.'Data.csv';
$csvfile = fopen($fileName, "w") or die("Unable to open file!");
fwrite($csvfile, $output);
fclose($csvfile);
As per my research or knowledge, I think there is a need to add some header (that specify fileName, fileSize and many other). I don't have much knowledge about it, why and where do i need to add it.
Can anyone help me out?
Upvotes: 1
Views: 502
Reputation: 11
Here you go the simple answer to your question.
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=testdata.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// fetch the data
$row = array(array('row1val','row1val','row1val'),array('row2val','row2val','row2val'));
// loop over the rows, outputting them
foreach($row as $fields):
fputcsv($output, $fields);
endforeach;
fclose($output);
?>
Thanks
Upvotes: 1