Home » excel » html – MySQL Export to Excel Writes Whole PHP File

html – MySQL Export to Excel Writes Whole PHP File

Posted by: admin May 14, 2020 Leave a comment


I am having an issue where when I go to write a MySQL table to an Excel file using PHP it writes the table, but then also writes the whole HTML document.

Here is the code I’m using to write Excel document:

   $filename = "list.csv"; 

   header("Content-Disposition: attachment; filename=$filename");
   header("Content-Type: application/vnd.ms-excel");
   header("Pragma: no-cache"); 
   header("Expires: 0");

   $fileData = "SELECT * FROM `Table` ORDER BY `Name`;";
   $info = $conn->query($fileData);

   $flag = false;
   while ($the_row = $info->fetch_assoc()) {
       if (!$flag) {
           echo implode(",", array_keys($the_row)) . "\r\n";
           $flag = true;
       echo implode(",", array_values($the_row)) . "\r\n";


I only want the file to export on button click, and it does export the table perfectly. Just not sure why it is also doing the whole html document.

Here is the HTML for the submit:

<form action="" method="post">
   <button class="btn right" type="submit" name="submit">Export List</button>
How to&Answers:

I’m just going to put an answer here so no one else tries to answer this anymore. an exit needs to be added after you mysqli_close($conn) otherwise this is why it’ll output the html