我正在尝试将数据从MySQL数据库导出到excel文件。这是我的代码 -
function cleanData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
//File to export
$filename = "export_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = mysqli_query($dbc, $query) or die('Query failed!');
while(false != ($row = mysqli_fetch_assoc($result))) {
if(!$flag) {
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
mysqli_close($dbc);
数据正常但标题是右移一行。其余数据从第1列开始。我该如何解决?