echo CSV data to browser for download - how to?

Permalink
Hello good people!

I'm trying to implement some code in a single_page dashboard controller to let me export some data from a database table as a CSV file - so far my code looks like:

Loader::library('3rdparty/adodb/toexport.inc');
$date = date('Y-m-d');
$filename = 'csvfile_'.$date.'.csv';
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename );
Loader::model('mymodel', 'mypackage');
$recordset = Model::export($_REQUEST);
echo rs2csv($recordset);


This totally works however I get a HTML warning message appended to the bottom of the CSV file that says "Warning: Cannot modify header information - headers already sent by...".

Is there a way to suppress this warning? Is there a way to make sure my stuff get outputted first? Is this the right way to do this?

Many thanks for any advice!
Cheers,

Alex

alexaalto
 
beebs93 replied on at Permalink Reply
beebs93
Hi Alex,

I ran into something similar with a single page, but I'm not sure it will help your specific situation.

I had a WP site from which I was sending a JSONP request to a single page on a C5 site (to sync some footer data). The single page's code was only to receive the request, fetch the relevant data using C5's environment, then json_encode and spit out the response.

The problem I had was since the header/footer files are automatically included in single pages I was getting that content outputted as well thus messing up my response.

Template (page type) files in your C5 theme directory are free to include/exclude said header/footer files, but single page PHP files MUST be in the /single_pages directory to be installed properly.

I had to first create the single page PHP file in the normal single_page directory, add it the usual way through the dashboard, then move the PHP file from the /single_pages directory to my /theme/my_theme directory.

Strangely enough, this did not "break" the sitemap and I could still access, move, modify attributes without any side effects.

Since it was now a faux-template file I didn't have the header/footer being automatically included in my Ajax response data.
alexaalto replied on at Permalink Reply
alexaalto
Many thanks for the reply beebs93!

I took a look at how it was done in "concrete/dashboard/reports/forms.php", which comes with Concrete5 - and it's so much more simple than I thought. You simply kill the process before it can finish outputting anything else by adding a "die;" statement. So it works perfectly with the exact same code above but with the addition of a final line: