3

I'm having some trouble getting nl2br to do what I want.

Can someone explain why nl2br doesn't change the \n in the JSON data to < br /> in my PHP?

Here is the code:

$page = file_get_contents('JSON_FEED_URL');
$page2 = nl2br($page);

When I echo $page2 and view the HTML page it comes out as a big wall of text.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141

4 Answers4

3

Try

$page = file_get_contents('JSON_FEED_URL');
$page2 = preg_replace("/\\n/m", "<br />", $page);  

As said, str_replace would also work a tad faster, but the above counts of multiline breaks.

Adam
  • 1,957
  • 3
  • 27
  • 56
3

nl2br does not replace the new lines, only ads the <br> tags. In HTML there is no need to remove the new line characters as they are considered to be white space which is collapsed to a single space for display. This fact is the very reason for having the <br> tag.

Kelly Copley
  • 2,990
  • 19
  • 25
2

Since you say that you can see the \ns when echoing (instead of a newline in the source), this probably means that your \ns are literal, and not "proper" newlines. This is because your JSON is read as a string. Fix this by calling json_decode();

$page2 = nl2br(json_decode($page));

Explanation:
The string

line1
line2

is in JSON saved as

"line1\nline2"

but that \n is not a real newline, just normal characters. By decoding the JSON, it will be correct.

Matsemann
  • 21,083
  • 19
  • 56
  • 89
0

nl2br did not interpret \n to <br /> in HTML because they were literal slashes followed by n.

On your source, the text looks like the following:

 FRIDAY THROUGH WEDNESDAY.\n\nMORE RAIN IS

Should be something similar to the ff so that it'll be interpreted:

 FRIDAY THROUGH WEDNESDAY.

 MORE RAIN IS

You can address your problem by using str_replace() or if you can update your code when putting content on "JSON_FEED_URL", add nl2br before putting those content.

kevinandrada
  • 449
  • 2
  • 5
  • 14