I have a function that basically on user request gets the data from the database exports it to csv file and then automatically downloads that csv file for the user. The function works as I expected however for some reason when the file that gets downloaded to the users computer it has some random html data in it. I am not sure how this is getting added to the file as I check the file that gets created on the server and there is no random text within it. Below is the function that I am using:
private function _exporte()
{
$file_name = "/path-". date('d-m-Y') .".csv";
if(file_exists($file_name) == TRUE)
unlink($file_name);
$file = fopen($file_name, 'w') or die ("Can not open file to write");
$file_vars = array();
$data = $this->name_model->get_data();
$headerDisplayed = false;
foreach($data as $row)
{
$file_vars['Code'] = $row['code'];
$file_vars['Category'] = $row['category'];
$file_vars['Category ID'] = $row['category_id'];
if(!$headerDisplayed)
fputcsv($file, array_keys($file_vars));
$headerDisplayed = true;
fputcsv($file, array_values($file_vars));
}
if (file_exists($file_name))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file_name));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_name));
readfile($file_name);
}
}