正在将 PHP 转换为 Excel,但在 Excel 文件中遇到问题,它没有在自己的单元格中添加每一行。它的外观如下:https://www.dropbox.com/s/64lz7lqy8z7x72j/export.csv 它把它写入第一个单元格,看起来它已经写入了所有单元格。
这是 PHP 代码:
<?php
$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('chart', $conn) or die(mysql_error($conn));
$result = mysql_query('SELECT * FROM chartgoogle', $conn) or die(mysql_error($conn));
header('Content-Type: text/csv'); // tell the browser to treat file as CSV
header('Content-Disposition: attachment;filename=export.csv'); // tell browser to download a file in user's system with name export.csv
$row = mysql_fetch_assoc($result); // Get the column names
if ($row) {
outputcsv(array_keys($row)); // It wil pass column names to outputcsv function
}
while ($row) {
outputcsv($row); // loop is used to fetch all the rows from table and pass them to outputcsv func
$row = mysql_fetch_assoc($result);
}
function outputcsv($fields) {
$separator = '';
foreach ($fields as $field) {
echo $separator . $field;
$separator = ','; // Separate values with a comma
}
echo "\r\n"; //Give a carriage return and new line space after each record
}
?>
最佳答案
试试这个:
function outputcsv($fields) {
$csv = '';
foreach ($fields as $field) {
$csv .= '"' . $field . '",';
}
$csv .= "\r\n"; //Give a carriage return and new line space after each record
echo $csv;
}
查看字段前后的双引号。 CSV 文件通常使用双引号作为闭包。他们称之为文本限定符。
关于PHP 将 mysql 转换为 excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22554464/