5

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.

Community
  • 1
  • 1
IAmNoob
  • 576
  • 4
  • 14

2 Answers2

2

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.

  • This is a misleading answer. From the PHP manual: **Returns string with
    or
    inserted before all newlines (\r\n, \n\r, \n and \r).**
    – mickmackusa Jun 22 '20 at 03:33
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);
Jagadeesh
  • 734
  • 6
  • 26