How to make a downloadable CSV export.

I have this piece of code here:

// output headers so that the file is downloaded rather than displayed
header(‘Content-Type: text/csv; charset=utf-8’);
header(‘Content-Disposition: attachment; filename=data.csv’);

// create a file pointer connected to the output stream
$output = fopen(‘php://output’, ‘w’);

// output the column headings
#fputcsv($output, array(‘Column 1’, ‘Column 2’, ‘Column 3’));

// fetch the data
mysql_connect(‘localhost’, ‘erlendanderson’, ‘ugumuq’);
$rows = mysql_query(‘SELECT osakond, soetusaasta, it_number, tooteruhm, mudeli_nimetus, sn, riigivara_nr, inventaari_nr, maja, ruum, vastutaja, markus FROM norse5_proov’);

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

I would like it to ask a download window so I can download the file automatically w/o having to copy-paste stuff.
How can I do that? thanks in advance

It looks to me that you have the header statements incorrectly specified to do what you want.

Try replacing them with
header(“Content-type: application/”);
header(“Content-disposition: filename=data.csv”);

I use this in one of my sites and it works fine.

it works now but the code puts all the data in the first column.
Any idea?

Yes, as it is a csv file you need to add commas between the fields.

You need to split the row by fields add a comma and then output it to the csv file.

I think you didn’t quite get it.
It adds commas perfectly. But in the excel file it puts all the data in the first column, first cell, second cell etc.
Here’s the screenshot:

It should place data sperated by commas into different columns, accordingly to the amount of words seperated by a comma.

Rename your output file with the csv extension and give that a try.

The code itself already gives it the .csv extension.
All the files I’ve downloaded are .csv files.

Sorry no real idea.

Try getting the free CSV ED programme from and see if that opens it in columns. If it does then there is a problem with your Excel installation, if not then there is a problem with the csv generation.

Well… Thank you for that link. It opens up perfectly and the data is in the correct column.
It’s just excel being a bitch.

Sponsor our Newsletter | Privacy Policy | Terms of Service