Mig
Mig

Reputation: 59

PHP MySQL Export data to excel

I have the following code to export the data from the table that the user choose, but for some reason it's not downloading the file..
here's my export.php:

<?php  
//export.php  
session_start();
$DataDeConsulta = $_SESSION['DataDeConsulta'];
//export.php  
$connect = mysqli_connect("localhost", "user", "pw", "filecleaner");
$output = '';
if(isset($_POST["export"]))
{
 $query = "SELECT * FROM filecleaner.`Opened_". $DataDeConsulta ."`";
 $result = mysqli_query($connect, $query);
 if(mysqli_num_rows($result) > 0)
 {
  $output .= '
   <table class="table" bordered="1">  
                    <tr>  
                         <th>Emails</th>  
                    </tr>
  ';
  while($row = mysqli_fetch_array($result))
  {
   $output .= '
    <tr>  
                         <td>'.$row["Emails"].'</td>  
                    </tr>
   ';
  }
  $output .= '</table>';
  header('Content-Type: application/xls');
  header('Content-Disposition: attachment; filename=download.xls');
  echo $output;
 }
}
?>

And on my index.php I have this:

<form method="post" action="export.php">
     <input type="submit" name="export" class="btn btn-success" value="Export" />
    </form>

It doesn't give me any error at all, just stay where it was and don't download anything

Upvotes: 0

Views: 573

Answers (3)

Korat Prakash
Korat Prakash

Reputation: 161

Try header code into top of the file and remove from bottom.

// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "download.xls"
header("Content-Disposition: attachment; filename=download.xls");

Upvotes: 0

Mig
Mig

Reputation: 59

Solved. :)

<?php  
//export.php  

session_start();
$DataDeConsulta = $_SESSION['DataDeConsulta'];

//export.php  
$connect = mysqli_connect("localhost", "user", "pw", "filecleaner");
$output = '';

 $query = "SELECT * FROM filecleaner.`Opened_". $DataDeConsulta ."`";
 $result = mysqli_query($connect, $query);
 if(mysqli_num_rows($result) > 0)
 {
  $output .= '
            Emails
  ';
  while($row = mysqli_fetch_array($result))
  {
    $output .= ''.$row["Emails"].'
    ';
  }
  header('Content-Type: application/csv');
  header("Content-Type: application/force-download");
  header('Content-Disposition: attachment; filename=ics2019.csv');
  //
  echo $output;
 }

?>

Upvotes: 1

mani
mani

Reputation: 11

Try This code

<?php  
ob_start();

---
---- 
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=members".date('d-m-Y').".csv");
echo $output;
ob_end_flush();
?>

Upvotes: 0

Related Questions