mcook16
mcook16

Reputation: 67

PHP array to CSV outputting entire html page

I am trying to output an array to CSV with PHP using the below code. It is, however outputting the entire HTML page to the CSV. How can I write this so it only outputs the array to the CSV and not the code of the page?

I believe the problem is to do with:

$f = fopen('php://output', 'w');
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://output', 'w');
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}

array_to_csv_download($data_array);

Upvotes: 0

Views: 168

Answers (1)

Progrock
Progrock

Reputation: 7485

You are sending output before your headers.

You can simplify to:

<?php
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    $f = fopen('php://output', 'w');
    foreach ($array as $line)
        fputcsv($f, $line, $delimiter);
}

Make sure you do not output anything else prior to those header calls.

Upvotes: 1

Related Questions