问题
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.
回答1:
Using array_map
you can call the function, so with the value of each $row
you can get the values.
$sql = "SELECT * FROM myTable";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$output[]=array_map("nl2br",$row);
}
echo json_encode($output);
回答2:
You need to know exactly what kind of text flow your json must send. Using php's nl2br function will replace newlines with a HTML tag named "br" 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.
来源:https://stackoverflow.com/questions/31099385/preserve-line-breaks-in-mysqli-fetch-assoc-php