0

I'm getting a feed that contains json data that is then decoded by php (json_decode) and echoed back out to my html page.

The feed contains \n characters but when the PHP echos them out, the HTML doesn't recognize them as new lines or line breaks so the HTML text just comes out as one big wall of text.

Can someone give me a hint as to what I should be doing to make the php echo out a
or something similar when the json data has \n in it?

As an example, the json data might contain "FRIDAY THROUGH WEDNESDAY.\n\nMORE RAIN IS" but when the HTML is generated it just looks like "FRIDAY THROUGH WEDNESDAY. MORE RAIN IS" all on the same line.

Thanks!

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

3 Answers3

2

Try:

echo nl2br($json_string);
Valeh Hajiyev
  • 3,216
  • 4
  • 19
  • 28
1

You must replace your '\n' with the equivalent in HTML, which is the br tag.

You can output your string in the following way :

echo str_replace("\n", "<br />", $yourString);
Dany Caissy
  • 3,176
  • 15
  • 21
  • The solution you posted prior to editing worked but I can't get it to work with nl2br. – Question Asker Jun 21 '13 at 15:03
  • Wierd, maybe it's your version of PHP? I put it back to how it originally was, for the sake of diversity. – Dany Caissy Jun 21 '13 at 15:06
  • Yeah maybe... do you know if nl2br works only when echoing? Because I have a bunch of echo statements that I didn't want to have to update I just tried changing the string like this: $page = nl2br(file_get_contents('JSON_FEED_URL')); – Question Asker Jun 21 '13 at 15:10
  • It won't only work while echoing, but it won't modify the string you pass to it. It will return the resulting string, so you need to either echo or save the string that it returns. – Dany Caissy Jun 21 '13 at 15:11
  • Thanks, I edited my above response about the same time you replied to show that I am passing the string to nl2br. Would you expect that to work? – Question Asker Jun 21 '13 at 15:16
  • It might work, but I'd recommend putting the result of file_get_contents into another variable first. Especially if it gives unwanted results and you want to print the result to see what is in it. – Dany Caissy Jun 21 '13 at 15:18
0

From php.net:

http://fr2.php.net/manual/fr/function.json-decode.php#112084

function json_decode_nice($json, $assoc = TRUE){
    $json = str_replace(array("\n","\r"),"\\n",$json);
    $json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$json);
    $json = preg_replace('/(,)\s*}$/','}',$json);
    return json_decode($json,$assoc);
}
Armel Larcier
  • 15,747
  • 7
  • 68
  • 89