John Higgins John Higgins - 2 months ago 18
PHP Question

Remove <br /> tags from PHP csv export

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

Answer

Stackoverflow do not let me comment without less than 50 reputation. Then I will put an answer (sorry!)

Have you tried str_replace? -> http://php.net/manual/es/function.str-replace.php

$html = 'Lorep Ipsum<br/>Dolor Sit Amet';

echo '<p>';
echo $html;
echo '</p>';

$replace = '<br/>';
$output = '';
$output = str_replace($replace, "", $html);

echo '<p>';
echo $output;
echo '</p>';

Output:

Lorep Ipsum
Dolor Sit Amet

Lorep IpsumDolor Sit Amet