0

I have troble geting this work and I can't figure it out what is the issue. I download a xls file, but it doesent opens. I had a mysql script like this, working, and I tried to convert it into mysqli and probably something is wrong... Thanks in advance

$sqlExp = "SELECT * FROM table";
    $countQryExp  = mysqli_query($link, $sqlExp );
  $filename = "sampledata.xls"; // File Name

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");

$flag = false;

while($row=mysqli_fetch_array($countQryExp,MYSQLI_ASSOC))
                {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\r\n";
      $flag = true;
    }
    echo implode("\t", array_values($row)) . "\r\n";
  }
Robert Rouge
  • 259
  • 1
  • 2
  • 9
  • 1
    Can you elaborate on what exactly the problem is? – Mureinik Feb 20 '15 at 19:55
  • If you're generating a csv file (whether you believe that's an Excel file or not) then use PHP's built-in [fputcsv()](http://www.php.net/manual/en/function.fputcsv.php) function rather than trying to write the same functionality (badly) yourself – Mark Baker Feb 20 '15 at 19:56

1 Answers1

1

There's a lot more to generating an Excel file than giving it a content type of application/vnd.ms-excel. Excel is a very particular format, whereas you're generating a TSV file - tab separated values, and in a pretty breakable manner (what happens if someone puts a \t in one of your site's fields, or a new line?).

If you want to generate real Excel files, you'll want one of the various libraries for doing so. If a CSV/TSV are fine, just export a .csv/.tsv file with proper headers.

Community
  • 1
  • 1
ceejayoz
  • 176,543
  • 40
  • 303
  • 368