I have created a page that populates an HTML table based on mysql/php. Now I am trying to create a link on the same page so that logged in users are able to download the same information in excel format.
I have used the code pasted below, and it does display the information but not in columns; it just shows as one massive line of text. Where have I gone wrong?
Thanks.
Code: Select all
<?php
require_once("models/config.php");
if(!isUserLoggedIn()) { header("Location: login.php"); die(); }
?>
<?PHP
mysql_connect('****', '*********', '**********') or die (mysql_error());
mysql_select_db('**********') or die (mysql_error());
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) { $str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel;");
$out = fopen("php://output", 'w');
$flag = false;
$result = mysql_query("SELECT * from Customer$loggedInUser->user_id") or die('Query failed!');
while(false != ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = true;
}
array_walk($row, 'cleanData');
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
?>