0

Im trying to make a CSV export from data entered in an array on my website. I was using this question to help me. I am getting the data that should be in the CSV echoed on my website but not exported to a file. This is the code that I took from the question:

        header( "Content-Type: text/csv;charset=utf-8" );
        header( "Content-Disposition: attachment;filename=\"$filename\"" );
        header("Pragma: no-cache");
        header("Expires: 0");

        $fp= fopen('php://output', 'w');

        foreach ($data as $fields){
            fputcsv($fp, $fields);
        }
        fclose($fp);
        exit();

I dont exactly understand what the header() functions are doing. How would I get this to download to a file?

if it helps my array is in this format:

$data = array(dataset1(array, of, data), dataset2(array, of, data), dataset#(array, of, data));

EDIT:My $data array is in a session varible and the reason it wasnt downloading was because there I had session_start() and some includes at the top. Instead of downloading it would echo to the screen but if I remove this it downloads at the cost of there being no data to export. Anyone have a solution to this?

Kynan Pacheco
  • 207
  • 2
  • 3
  • 10
  • 1
    They declare the file as a CSV file using character set UTF-8, and name the file accordingly. This is an excellent tutorial. --->http://code.stephenmorley.org/php/creating-downloadable-csv-files/ – clearshot66 Jun 30 '17 at 15:50
  • 1
    By sending the HTTP header "Content-Disposition: attachment;" you tell the browser that it should not display the output but download it as a file with the name you specified in $filename. So actually this code SHOULD trigger the download of a file. – masterfloda Jun 30 '17 at 16:30

1 Answers1

0

The header() function is sending HTTP headers to your browser with the respective values. It then sends the CSV data to the output stream which the browser interprets as a downloadable file due to the headers.

kgrwhite
  • 106
  • 1
  • 7