Export CSV File

I have a single page and in the controller a function which queries the database and formats the results into csv format. What i want to do is prompt the browser. I have my headers but if i echo to the single page it does nothing. If i put the code in the view function it will download when i visit the page, but i want to pass parameters to it first.

Does any one know how can i get the browser to prompt for the download?

View Replies: View Best Answer
mhawke replied on at Permalink Best Answer Reply
Just a concept... can you use the single page to build a link to the view.php that includes the required parameters so you end up with a link something like this rendered on your single page:

<a href="path/to/view.php?column1=first_name&column2=last_name">Download CSV file</a>
kingdt replied on at Permalink Reply
Thanks mhawke, works a treat.

What i did was to create a new empty single page and copy my existing controller with the code. I'm using a select list to select a date, so i changed the href attribute of the link each time a new date was selected.

My js in the page to change the link
   var weekLink = '<?php echo $this->url('/download_times/request/?week_date=') ?>';
   var weekDate = $('#week_list option:selected').text();
   var link = document.getElementById("requestLink");
   link.setAttribute("href", weekLink + weekDate);
   return false;

My link
<a href='#' id="requestLink">Download Times</a>

My controller
public function view(){
   $db = Loader::db();
   $js = Loader::helper('json');
   $week_date = $_REQUEST['week_date'];
   $sql = "SHOW FIELDS FROM table";
   $colResult = $db->GetAll($sql);
   $headRow = [];
   foreach($colResult as $row){ $headRow[] = $row[Field]; }
   // Fetch Record from Database
   $sql = "SELECT * FROM table WHERE week_date = ?";
   $rowResult = $db->GetAll($sql,array($week_date));
   header("Content-type: text/csv");  
   header("Cache-Control: no-store, no-cache");  
   header('Content-Disposition: attachment; filename="hi.csv"'); 
   $out = fopen('php://output', 'w');