Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Displaying CSV File in Internet Explorer

Tags:

php

csv

Greeting Experts,

I have a php script that queries our db and spits out a csv file in a browser. This work greate in FireFox, Safari, and Chrome. It does not work in Internet Explorer, which is the default browser in our building (sigh). I cannot post the url as it is a protected site and wouldn't do you any good.

In IE I get two popup windows when I click the linke to this report:

1) Unable to download downloads.html from . Unable to open this Internet Site. The request site is either unavailable or cannot be found Please try again later.

2) a downloads % info window: Getting File Information: downloads.html from Estimated time left: Download to: Transfer rate: all these are empty.

So, I have an page, downloads.html trying to produce a CSV file. Not sure what is bombing here as far as IE goes. Are there different headers I can try? I haven't seen any in my searching.

Thanks for any tips...

Here is my function that prints out the data:

# $data is array of data from database
function render_excel($data) {
  # headers for browsers
  header("Content-type: text/csv");
  header("Content-Disposition: attachment; filename=file.csv");
  header("Pragma: no-cache");
  header("Expires: 0");

  # column headers
  $column_headers = "Filename, Link to File, Details, Unique Viewers\n";
  $rows = '';
  foreach($data as $foo => $arr){   
    $rows .= $arr['filename'].",";
    $rows .= $arr['resource_url'].",";
    $rows .= $arr['detail_url'].",";
    $rows .= $arr['distinct_views']."\n";
  }
  print $column_headers;
  print $rows;
}
like image 345
John Cowan Avatar asked Dec 01 '25 23:12

John Cowan


1 Answers

There are two problems I think. First is that you need quotes around the filename and second is that you need to add a Content-Length header to show download times.

//1
header("Content-Disposition: attachment; filename=\"file.csv\"");

//2
header("Content-Length: " . (strlen($column_headers.$rows)));

Keep in mind that the length might be different if you have other code on your page.

like image 142
Hugo Delsing Avatar answered Dec 03 '25 15:12

Hugo Delsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!