I am trying to create a button that will force a CSV file download but for some reason I am not able to get it working. This is the code that I have:
public
Well. you may try this, it'll work if your result is not empty
public function export_to_csv($result)
{
if(!$result) return false;
ob_end_clean();
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename=pedidos.csv');
$fp = fopen('php://output', 'w');
$headrow = $result[0];
fputcsv($fp, array_keys($headrow));
foreach ($result as $data) {
fputcsv($fp, $data);
}
fclose($fp);
$contLength = ob_get_length();
header( 'Content-Length: '.$contLength);
}
Put this code below your loop.
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="pedidos.csv"');
echo $shtml;
How did you find out the content type application/force-download? I've never heard of it. The proper MIME type for CSV is text/csv
You can find more examples how to use header function in php manual
You need also display $shtml
you didn't do it in your code.
you need to echo
your content after the header
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename=pedidos.csv');
echo $shtml