My database:
I am having a issue exporting my data to excel due to the comma in the "description" field in my database.
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 .="
";
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 .="
";
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:
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.
Here's the link to the php doc page: http://php.net/manual/en/function.fputcsv.php
If you need anything over an above simple reading then maybe have a look at PHPExcel