This class can generate the necessary request headers to make the outputted HTML be downloaded as a file by the browser with a file name that makes the file readable by Excel(.xls),Word(.doc) and CSV(.csv).
ExportPHP.class.php
<?php class ExportPHP { // method for Excel file function setHeaderXLS($file_name) { header("Content-type: application/ms-excel"); header("Content-Disposition: attachment; filename=$file_name"); header("Pragma: no-cache"); header("Expires: 0"); } // method for Doc file function setHeaderDoc($file_name) { header("Content-type: application/x-ms-download"); header("Content-Disposition: attachment; filename=$file_name"); header('Cache-Control: public'); } // method for CSV file function setHeaderCSV($file_name) { header("Content-type: application/csv"); header("Content-Disposition: inline; filename=$file_name"); } function exportWithQuery($qry,$file_name,$type) { $tmprst=pg_query($qry); $header='<center><table width="100%">'; $num_field=pg_num_fields($tmprst); while($row=pg_fetch_array($tmprst)) { $body.="<tr>"; for($i=0;$i<$num_field;$i++) $body.="<td>".$row[$i]."</td>"; $body.="</tr>"; } if($type=='xls') $this->setHeaderXLS($file_name); else if($type=='doc') $this->setHeaderDoc($file_name); else if($type=='csv') $this->setHeaderCSV($file_name); echo $header.$body."</table>"; } } ?>
Step 2: Create PHP file named 'connection.php' for database connection.
connection.php
<?php $con = "dbname=dbname user=username password=pass host=127.0.0.1 port=5432"; $dbcon = @pg_connect($con); ?>
Step 3: Create PHP file named 'exportgateway.php'.
In this file, we need to create an object of ExportPHP class.
Create a query which is needed to be outputted.
Call the method 'exportWithQuery' with parameters Query, filename,filetype
<?PHP include_once('ExportPHP.class.php'); include('connection.php'); $exp=new ExportPHP(); $qry='SELECT * FROM "tablename"'; //Note: Please use anyone of the below code.Or make proper conditions //Export to XLS $exp->exportWithQuery($qry,"report.xls","xls"); //Export to DOC $exp->exportWithQuery($qry,"report.doc","doc"); //Export to CSV $exp->exportWithQuery($qry,"report.csv","csv"); ?>
Ref: http://www.phpclasses.org
This comment has been removed by a blog administrator.
ReplyDelete