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!

3
  • i don't think this is a problem with your json - how are you displaying it? Commented Jun 21, 2013 at 14:45
  • 1
    Wrap the echoed content in <pre> tags Commented Jun 21, 2013 at 14:45
  • probalby the duplicate of that stackoverflow.com/questions/42068/… Commented Jun 21, 2013 at 14:49

3 Answers 3

2

Try:

echo nl2br($json_string);
Sign up to request clarification or add additional context in comments.

Comments

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);

6 Comments

The solution you posted prior to editing worked but I can't get it to work with nl2br.
Wierd, maybe it's your version of PHP? I put it back to how it originally was, for the sake of diversity.
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'));
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.
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?
|
0

From php.net:

https://www.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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.