<?php
// Export MySQL table to Excel
//
// Written by Mark Jackson @ MJDIGITAL
// Can be used by anyone - but give me a nod if you do!
// http://www.mjdigital.co.uk/blog

// FILENAME
$filename        'export.xls';

// TABLE
$table_name        '__MY_TABLE__';

// DATA ORDER
$orderBy        '__ORDER_BY_FIELD__';
$orderDirection    '__ORDER_DIRECTION__'// can be left blank

// DB Details
$hostname "__DB_HOST__";
$database "__DB_DATABASE__";
$username "__DB_USERNAME__";
$password "__DB_PASSWORD__";

// show errors (.ini file dependant) - true/false
$showErrors true;








//////////////////////////////////////////////////////
//
//        DO NOT EDIT BELOW
//
//////////////////////////////////////////////////////

if($showErrors) { error_reporting(E_ALL);    ini_set('error_reporting'E_ALL);    ini_set('display_errors',1); }

function 
cleanData($str) { 
    
$str preg_replace("/\t/"" "$str); // clean out tabs in data - replace with space
    
$str preg_replace("/\n/"", "$str); // clean out line breaks and replace with comma+space
    
$str preg_replace("/\r/"""$str); // clean out extra line breaks
    
return $str;


$MJCONN mysqli_connect($hostname$username$password$database);
$query_rsExport "SELECT * FROM $table_name ORDER BY $orderBy $orderDirection";
$rsExport mysqli_query($MJCONN,$query_rsExport) or die(mysql_error());
$fields mysqli_fetch_fields($rsExport);
$row_rsExport mysqli_fetch_assoc($rsExport);
$totalRows_rsExport mysqli_num_rows($rsExport);

$d "\t";
$nl "\n";

$contents '';

// write out fields
foreach($fields as $field) {
    
$contents .= $field->name.$d;
}
// close fields list
$contents .= $nl;

// write out data
do {
    foreach(
$fields as $field) { // loop through fileds to output
        
$contents .= cleanData($row_rsExport[$field->name]).$d;
    }
    
// close record line
    
$contents .= $nl;
}while(
$row_rsExport mysqli_fetch_assoc($rsExport));

// free memory
mysqli_free_result($rsExport);

// Send Headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename='.$filename);

echo 
$contents;

exit;
?>