Export Mysql Data with php

1

Greetings, I'm trying to export mysql data to an EXCEL using php,

The problem I have is that when I try to export the data is not exported, that is, it shows the data on the screen again, but it does not give me the window to export ..

          <?php $output = '';      if(isset($_POST["export_excel"]))  {     $sql = "SELECT * from tblaccounts inner join tblinvoiceitems on tblinvoiceitems.invoiceid=tblaccounts.invoiceid WHERE tblaccounts.date BETWEEN '2015-12-25 0:00:00' AND '2016-09-20 23:59:00'"; $result = mysql_query($sql);


     $output .= '<table>
<tr>
<th>Transaction Date</th>
<th>Invoice Number</th>
<th>User ID</th>
<th>Company Name</th>
<th>Payment Method</th>
<th>Description (Package or Service)</th>
<th>Amount</th>
<th>Tax</th>
<th>Tax Amount</th>
<th>Total</th>
</tr>'; 
     while ($r2 = mysql_fetch_array($result)){ echo "<tr>"; echo '<td>'.$r2["duedate"].' </td>'; echo '<td>'.$r2["invoiceid"].'</td>'; echo '<td>'.$r2["userid"].'</td>'; $r9 = mysql_fetch_array(mysql_query("SELECT * FROM tblclients WHERE id=$r2[userid]")); echo '<td>'.$r9["companyname"].'</td>'; echo '<td>'.$r2["paymentmethod"].'</td>'; echo '<td>'.$r2["description"].'</td>'; echo '<td>'.$r2["amount"].'</td>'; echo '<td>'.$r2["taxed"].'</td>'; if ($r2["taxed"] == 0 ) { $r3 = mysql_fetch_array(mysql_query("SELECT * FROM tbltax WHERE id = $r2[taxed] ")); echo "<td> no tax </td>"; echo '<td>'.$r2["amount"].'</td>';  } else { $r3 = mysql_fetch_array(mysql_query("SELECT * FROM tbltax WHERE id = $r2[taxed] ")); $r6 = $r2["amount"] / $r3["taxrate"]; $r8 = $r6 + $r2["amount"]; echo "<td> $r6 </td>"; echo "<td> $r8 </td>"; } echo " </tr>"; }  $output .= '</table>'; header("Content-Type: application/xls");   header("Content-Disposition: attachment; filename=download.xls");  echo $output;  } ?>   

Well, the code will get him out of here: link

I modified it a bit because I'm using mysql_query and not mysqli_query ..

Can someone help me?

    
asked by Jesús Suárez 11.09.2016 в 11:57
source

1 answer

1

Replace the header("Content-Type: application/xls"); header("Content-Disposition: attachment; filename=download.xls"); headers at the end of the code that you shared with the following:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='download.xls');

This is what is recommended in the PHP documentation to force it to download and not show the contents of a file.

By the way, what you are really doing is exporting a document with an HTML table that is saved with the XLS extension and that mysteriously Excel also imports correctly. But since it was not your question, I'm just saying this.

Greetings: -)

    
answered by 11.09.2016 в 13:35