Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve line breaks in mysqli fetch_assoc( ) PHP

Tags:

php

mysqli

I am trying to get all the rows from my MySQL database using the following code:

$sql = "SELECT * FROM myTable";
$result = $conn->query($sql);
    while($row = $result->fetch_assoc()) {
        $output[]=$row;
    }
echo json_encode($output);

My question is, How to preserve the line breaks using this code? I can preserve line breaks using nl2br() when I need a particular string for example

nl2br($_row['fieldName']);

but I want to know How can I use the same nl2br() when fetching the result in an array?

I have referred this question as well but this explains just for a single string not the array.

If there is no way of doing it, please suggest me some other way of doing it.

like image 513
IAmNoob Avatar asked Oct 19 '22 08:10

IAmNoob


1 Answers

You need to know exactly what kind of text flow your json must send. Using php's nl2br function will insert a HTML tag named "br" before newlines used for displaying linebreaks when a browser render HTML. If the application that you feed with this json flow is expecting plain text and not HTML, using nl2br is not the right solution. In this case, I suggest to replace newlines with an escaped sequence as "\n" in your string before sending it as a parameter to the json_encode function, and to handle the decoding in your json flow consumer code adequately regarding what you want to do with it, html or anything else. In this case, this question may help.

like image 179
Guillaume Pagnard Avatar answered Oct 27 '22 21:10

Guillaume Pagnard