Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- ob_start();
- // Script for downloading MySql table in Excel
- /**
- * @author sapta
- * @copyright 2009
- */
- $cdate = date("Y-m-d"); // get current date
- // configuration
- $mysql_host = '';
- $mysql_user = '';
- $mysql_pass = '';
- $mysql_db = '';
- $query_string = "select * from sdm";
- $export_filename = "exported_table_on_$cdate.xls";
- // connect to mysql server
- $mysql_link = mysql_connect($mysql_host,$mysql_user,$mysql_pass);
- mysql_select_db($mysql_db,$mysql_link);
- // query from table
- $result = mysql_query($query_string);
- $count = mysql_num_fields($result);
- // fetch table header
- $header = '';
- for ($i = 0; $i < $count; $i++){
- $header .= mysql_field_name($result, $i)."\t";
- }
- // fetch data each row, store on tabular row data
- while($row = mysql_fetch_row($result)){
- $line = '';
- foreach($row as $value){
- if(!isset($value) || $value == ""){
- $value = "\t";
- }else{
- # important to escape any quotes to preserve them in the data.
- $value = str_replace('"', '""', $value);
- # needed to encapsulate data in quotes because some data might be multi line.
- # the good news is that numbers remain numbers in Excel even though quoted.
- $value = '"' . $value . '"' . "\t";
- }
- $line .= $value;
- }
- $data .= trim($line)."\n";
- }
- # this line is needed because returns embedded in the data have "\r"
- # and this looks like a "box character" in Excel
- $data = str_replace("\r", "", $data);
- # Nice to let someone know that the search came up empty.
- # Otherwise only the column name headers will be output to Excel.
- if ($data == "") {
- $data = "\nno matching records found\n";
- }
- // create table header showing to download a xls (excel) file
- header("Content-type: application/octet-stream");
- header("Content-Disposition: attachment; filename=$export_filename");
- header("Cache-Control: public");
- header("Content-length: ".strlen($data)); // tells file size
- header("Pragma: no-cache");
- header("Expires: 0");
- // output data
- // echo $header."\n".$data;
- echo $data;
- ?>
Add Comment
Please, Sign In to add comment