Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Forcing download of a csv file


Go to End


3 Posts   1532 Views

Avatar
Bruce B

Community Member, 164 Posts

5 February 2016 at 1:59pm

I am generating a page which is csv formatted data to allow my client to download some data. Linking to this page just displays the data in the browser, forcing the client into an extra step to save it as a csv. The page with the link is here:
http://demo.frogmouth.com.au/all-bookings/
I'm sure its possible to force this to download the file rather than display it but I lack the necessary knowledge.

This page is normally restricted to administrators only. In that case, right-clicking on the link to download the page, downloads the login error page instead. So that neat work-around doesn't work.

cheers
Bruce

Avatar
Kirk

Community Member, 67 Posts

5 February 2016 at 3:14pm

You need to set the headers up correctly so the visiting browser knows that it is a CSV file and that is has to be downloaded as a attachment.
This can be done in SilverStripe using the standard php header function.
You may need to create a simplified template (i.e just the content variable) and add a getContent method or amend your existing methods which output the data.

http://stackoverflow.com/questions/1465573/forcing-to-download-a-file-using-php

Avatar
Bruce B

Community Member, 164 Posts

8 February 2016 at 12:38pm

Thanks Kirk,
My template is now just the code to generate the CSV:

Workshop title, Booking type, No of bookings, Name, Email, Phone, Address, Booking ref, Booking date
<% loop EveryOrder %><% loop Items %>$TableTitle, <% if SubTitle %>$SubTitle, <% else %>, <% end_if %>$Quantity, <% with Order %>$Name, $Email, <% with shippingaddress %>$Phone<% end_with %>, "$ShippingAddress", $Reference, $Placed.Nice<% end_with %>
<% end_loop %><% end_loop %>

The page controller now includes the following:

public function index(SS_HTTPRequest $request) {
        $this->response->addHeader("Content-disposition", "attachment; filename=bookings.csv");
}

This forces the page to download rather than display in the browser. The only 'slight' problem is that the resulting file is empty.