[英]Export data from PHP to Excel with comma issue
My database: 我的数据库:
I am having a issue exporting my data to excel due to the comma in the "description" field in my database. 由于数据库中“说明”字段中的逗号,我无法将数据导出到excel。
Here is my code: 这是我的代码:
<?php
include 'database.php';
if (isset($_POST['submit'])){
$filename = 'uploads/'.strtotime("now").'.csv';
$fp = fopen($filename, "w");
$sql = "SELECT * FROM data";
$linkSql = mysqli_query($link,$sql) or die(mysqli_error($link));
$row = mysqli_fetch_assoc($linkSql);
$seperator ="";
$comma = "";
foreach ($row as $name => $value) {
$seperator .= $comma . '' .str_replace('','""',$name);
$comma = ",";
}
$seperator .="\n";
fputs($fp, $seperator);
mysqli_data_seek($linkSql, 0);
while($row = mysqli_fetch_assoc($linkSql)){
$seperator ="";
$comma = "";
foreach ($row as $name => $value) {
$seperator .= $comma . '' .str_replace('','""',$value);
$comma = ",";
}
$seperator .="\n";
fputs($fp, $seperator);
} fclose($fp);
} ?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="post" action="export.php">
<input type="submit" name="submit" value="export">
</form>
</body>
</html>
And here is the data after I export to excel: 这是我导出到excel后的数据:
The issue is you're implementing something needlessly and have to solve all the tedious issues others before you have already addressed. 问题是您正在不必要地实施某些工作,并且必须先解决其他所有繁琐的问题,然后再进行解决。
There's a wonderful built in function called fputcsv()
that handles seperators and enclosures to escape your content fields very well. 有一个很棒的内置函数
fputcsv()
,它处理分隔符和附件以很好地转义您的内容字段。
Here's the link to the php doc page: http://php.net/manual/en/function.fputcsv.php 这是php doc页面的链接: http : //php.net/manual/en/function.fputcsv.php
如果您需要以上简单的阅读内容,那么可以看看PHPExcel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.