Tommizzy
Tommizzy

Reputation: 161

Wordpress converting array to csv for download

I have the following function that takes an array of results from a database query. I populate the array as I loop through the query results. At the same time I create an html table. After outputting the html table I call the function download_csv($csvArray) but no downloading of the CSV happens, It just displays the contents of the the array as if I did a var_dump on the array. I can confirm that the contents of the array are correct.

Note: this is being done on an external web page not from the admin area.

Is there some wordpress function that needs to be called to allow the download or am I missing something?

function download_csv($csvArray) {
    $file_name = 'report.csv';
    //output headers so that the file is downloaded rather than displayed
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename=$file_name");
    //Disable caching - HTTP 1.1
    header("Cache-Control: no-cache, no-store, must-revalidate");
    //Disable caching - HTTP 1.0
    header("Pragma: no-cache");
    //Disable caching - Proxies
    header("Expires: 0");

    //Start the ouput
    $output = fopen("php://output", "w");

    //Then loop through the rows
    foreach ($csvArray as $fields) {
        fputcsv($output, $fields);
    }
    //Close the stream off
    fclose($output);
    die();
}

Upvotes: 0

Views: 1553

Answers (1)

Thilak
Thilak

Reputation: 19

Following Code will help you to convert Array to CSV and Make it to automatically download Change the die(); function to exit(); And Use Implode function. It will work.

header('Content-Type: text/csv; charset=UTF-8');
  header('Content-Disposition: attachment; filename=sample.csv');
  header('Pragma: no-cache');
  header('Expires: 0');
  $fp = fopen('php://output', 'w');
  //ex: $list={...};


  foreach ($list as $fields) 
  {
  fputcsv($fp,implode($fields, ','));
  }
  fclose($fp);
  exit();

Upvotes: 1

Related Questions