I have a report that I want to allow users to pull the current data for into a downloadable .csv file.
I am currently using unmanaged_write_submit but this just prints the csv to the screen and users would have to right click and save as. I want to make it as easy as possible, by allowing the actual file to be downloaded through a button click.
$page['submit'] = array(
'#type' => 'submit',
'#value' => 'Download Report',
'#submit' => array('test_unmanaged_write_submit'),
);
function test_unmanaged_write_submit($form, &$form_state) {
//$data is pulling the .csv/query data
$data = get_array_data($form,&$form_state);
$destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
// With the unmanaged file we just get a filename back.
$filename = file_unmanaged_save_data($data, $destination, FILE_EXISTS_REPLACE);
if ($filename) {
$url = file_create_url($filename);
$_SESSION['file_example_default_file'] = $filename;
drupal_set_message(t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)', array(
'%filename' => $filename,
'@uri' => $filename,
'!url' => l(t('this URL'), $url),
)));
}
else {
drupal_set_message(t('Failed to save the file'), 'error');
}
}
But this only provides a link to a webpage that displays the .csv on the screen. Is there another drupal function or way to force a file download in php?