Problem in outputting to browser

I am using Php Excel,I am creating export button to my page. Is there a way to export the excel file without saving it to my server?.I tried it but the exported excel is corrupted.

<?php



require_once dirname(__FILE__) . '/phpexcel/Classes/PHPExcel.php';

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');


    $objPHPExcel = new PHPExcel();




    $result = mysql_query("select * from employee");


    $headings = array("ID","employeeid","employeefirstname","employelastname");

    $headingrow = 1;
    $colheader = 'A';
    foreach ($headings as $heading) {

        $objPHPExcel->getActiveSheet()->setCellValue($colheader.$headingrow, $heading);
        $colheader++;
    }


    $row = 2; 
    while($row_data = mysql_fetch_assoc($result)) {
        $col = 0;
        foreach($row_data as $key=>$value) {
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($col, $row, $value);
            $col++;
        }
        $row++;
    }



    $objPHPExcel->getActiveSheet()->setTitle('test');

    $objPHPExcel->setActiveSheetIndex(0);


     $filename = 'test.xls';

  header("Content-type: application/vnd.ms-excel");
  header("Content-Disposition: attachment; filename=\"$filename\"");
  header('Content-Transfer-Encoding: binary');

  $objWriter->save('php://output');
  exit;

?>

You could try saving excel document to temporary file and then via file_get_contents get the excel content and then output it. Another workaround you could use is saving the excel content to the php://memory and then output it, there’s example of using php://memory: an example.

Have you tried saving the relevant worksheet as a csv file then using http://uk1.php.net/manual/en/function.fgetcsv.php to read the csv file into PHP?

btw, are you aware that the mysql_* extension is now deprecated as of version 5.5 habd likely has been removed from PHP version 5.6 (anyone running 5.6 able to confirm), if not it’ll likely be removed from version 5.7. You should now be using either the mysqli_* extension or PDO (either way you should be using prepared statements)

Thank you it’s working now. :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.