I need to create a task for a cron job that exports data to a csv file, saves it and then emails it to a given email address. What I have done so far is...
if(!empty($data)){
//create CSV
$filename = 'ProductsOrdered-'.$today.'.csv';
$separator = $this->csvSeparator;
$csvColumns = array('ProductID', 'Product Title', 'MYOB Code', 'Order Date', 'Quantity', 'Total Value');
$fileData = '';
if($this->csvHasHeader) {
$headers = array();
// determine the CSV headers. If a field is callable (e.g. anonymous function) then use the
// source name as the header instead
foreach($csvColumns as $columnSource => $columnHeader) {
$headers[] = (!is_string($columnHeader) && is_callable($columnHeader)) ? $columnSource : $columnHeader;
}
$fileData .= "\"" . implode("\"{$separator}\"", array_values($headers)) . "\"";
$fileData .= "\n";
}
$items = $data;
foreach($items as $item) {
$columnData = array();
foreach($item as $e) {
$value = str_replace(array("\r", "\n"), "\n", $e);
$columnData[] = '"' . str_replace('"', '""', $value) . '"';
}
$fileData .= implode($separator, $columnData);
$fileData .= "\n";
}
$csv = SS_HTTPRequest::send_file($fileData, $filename, 'text/csv');
$f = new File();
$f->ClassName = 'File';
$f->Name = $filename;
$f->Title = $filename;
$f->Filename = 'assets/Uploads/Reports'.$filename;
$f->write();
//email the report
$to = 'email@somewhere.com.au';
$subject = 'Products Ordered Yesterday';
$from = 'email@somewhere.com.au';
$email = new Email($from, $to, $subject);
$email->setTemplate('ReportEmail');
$email->attachFile('/assets/Uploads/Reports/'.$filename.'');
$email->send();
}
Which I have mostly borrowed from the GridFieldExportButton class. Unfortunately it is not working. The file neither downloads automatically or saves in the assets folder. The data is def not empty as I can print it out to the screen, its just not doing anything.
Any pointers would be fabulous.