I am trying to perform functions exporting and importing CSV file.
I have done importing file successfully, but while exporting file, the downloaded CSV file contains HTML code with header, body and footer. I think that was from default.ctp, not sure.
Why, and from where, is that code automatically embedded ?
<?php function export()
{
$fp = NULL;
$results = NULL;
$row = NULL;
$results = $this->Order->find('all',array('fields'=> array('Order.sku','Order.inventory')));
$fp = fopen('php://output','w+');
$filename = "results.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment;');
fputcsv($fp,array(
'sku',
'inventory'
));
$ctr = count($results);
print($ctr);
foreach($results as $row)
{
fputcsv($fp,array(
$row['Order']['sku'],
$row['Order']['inventory']
));
}
fclose($fp);
} ?>
You need to disable layout rendering, stick this in your controller action:
Tehnichally, this is not the correct way to do CSV, you should create a CSV layout and view, but if it works, ce le vie.