0

I am creating a csv file to download, using a technique similar to using the browser prompt to download a file

$csv_export = .... csv data...;
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=" . $csv_filename . "");
echo($csv_export);
exit;

The file downloads just fine. But this is in WordPress, so when I do a php exit; everything stops and the page appears to hang, and the user needs to do a page reload.

Is there any way to do this and/or force a reload so that it does not appear to user to have hung?

Thanks

Fred Andrews
  • 648
  • 9
  • 18

1 Answers1

0

First of all, why do you use exit in the first place to stop the processing? You could output your content like this too:

clearstatcache();
header('Content-Type: '.$type);
header("Content-Disposition: attachment; filename=".$filename);
header('Content-Length: ' . filesize($path));
readfile($path);

If you really want the processing to stop and didn't send any HTML content you can just use the header redirect:

header("Location: http://example.com/myOtherPage.php");
die();

If you already send content, you could use JavaScript to reload, but I can't give you an example without more context/code.

Alex
  • 1,857
  • 3
  • 36
  • 51
  • Setting the header to a new page and calling die makes it so no file is saved, and wreaks havoc with Wordpress - get new page at bottom of current. What did you mean with readfile($path) ? Saving the content to a file and then re-reading it? – Fred Andrews Apr 05 '18 at 00:13
  • `readfile` (http://php.net/manual/de/function.readfile.php) will put the file to the output buffer and allow the user to "save" it with the browser promt – Alex Apr 05 '18 at 11:03
  • Using readfile as suggested allows the user to save the file (as did my original code using echo) but the Wordpress page still hangs. I think the problem is in setting the header, which screws up what Wordpress is doing next. I'm thinking maybe creating a download link on a new page is the only way to do this. – Fred Andrews Apr 06 '18 at 02:54