I am using the following code to export data into a CSV file using PHP. The problem is that one of the fields has line breaks in it the CSV file shows multiple <br />
tags. Is there an easy way to remove these from the output file?
<?php
$query = "SELECT * FROM table";
$result = $conn->query($query);
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=output.csv');
$row = mysqli_fetch_assoc($result);
if ($row) {
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysqli_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
Thanks,
John
Have you tried str_replace? -> http://php.net/manual/es/function.str-replace.php
$html = 'Lorep Ipsum<br/>Dolor Sit Amet';
echo '<p>' . $html . '</p>';
$html= str_replace('<br/>', "", $html);
echo '<p>' . $html . '</p>';
Output:
Lorep Ipsum
Dolor Sit Amet
Lorep IpsumDolor Sit Amet
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.