Create and download excel file – PHP

<?php
 $file = 'excelFile-'.date("Y-M-D")."-".time().'.xls';
 ob_start();
 echo '<table border="1"> ';
 echo '<tr><th>Product Name </th><th>Category</th><th>Active</th></tr>';
 for ($i=0; $i<=10; $i++) {
  echo "<tr><td>Product$i</td><td align='center'>Category $i</td><td>Active</td></tr>";
 }
 echo '</table>';
 $content = ob_get_contents();
 ob_end_clean();
 header("Expires: 0");
 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 header("Cache-Control: no-store, no-cache, must-revalidate");
 header("Cache-Control: post-check=0, pre-check=0", false);
 header("Pragma: no-cache");  header("Content-type: application/vnd.ms-excel;charset:UTF-8");
 header('Content-length: '.strlen($content));
 header('Content-disposition: attachment; filename='.basename($file));
 echo $content;
 exit;
?>

Leave a Reply

Your email address will not be published. Required fields are marked *