1
votes

I have the following script that will export data from my database using php to csv file. Everything works fine, except when I try to open the file in excel, I get "file is corrupt". When I run this code it shows the error - "The file is corrupted and can not be opened." Thanks in advance!

<?php

// Connection
include_once('conn.php');

$sql = "select * from info";
$qur = mysql_query($sql);

// Enable to download this file
$filename = "sampledata.csv";

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv");

$display = fopen("php://output", 'w');

$flag = false;
while($row = mysql_fetch_assoc($qur)) {
    if(!$flag) {
      // display field/column names as first row
      fputcsv($display, array_keys($row), ",", '"');
      $flag = true;
    }
    fputcsv($display, array_values($row), ",", '"');
  }

fclose($display);
exit;
?>
1
Try opening the file in notepad or some other text editor. Does it look like there are any problems?Jonathan Kuhn
Obligatory: The mysql_ extensions are deprecated, please upgrade to mysqli_ or PDO.Jay Blanchard
@JonathanKuhn: yes its working with other text editors like notepad, openoffice etc but not in MS Excel.Riken Shah
@JayBlanchard: I changed to mysqli but still it shows the error when opening the csv file in MS Excel.Riken Shah
Can you post a sample csv file? The code shown doesn't have any sort of obvious problems.Jonathan Kuhn

1 Answers

0
votes

I found the answer of my own question. Just need to add the ob_clean() line before we call the headers to download csv file to clear the output buffer. This will solve the error of not opening csv file in excel.