1

I cannot get the below array to replace the carriage return and newline with an HTML break <br />

JSON Array:

{"Fruit":"Apple","Veggies":"Carrot\r\nCelery\r\n\r\nCucumbers"}

I'm trying this and having no luck:

$html = json_decode(nl2br($json),true);

The line breaks are visible in the source code of the HTML itself however I cannot get the <br /> code to replace the 'newlines'.

I've tried this suggestion as well and it did not work either: Replacing \r\n (newline characters) after running json_encode

1
  • how did you get the json? I think is better replace before make the json encode or after if you dont have the possibility of edit the json Commented Jan 31, 2014 at 4:33

4 Answers 4

2

Run nl2br() after JSON is decoded, not on the JSON array source.

Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps you should try

$arJson = array( 'fruit' => 'apple', 
                 'veggies' => array( 'carrot', 'celery', 'cucumbers' ) );

header( 'Content-Type: application/json' );

print json_encode( $arJson );

Which returns a JSON

Then use jQuery or your favorite library( even a custom build one ) to send an ajax request to the page.

$.ajax({

    url: 'frtsnvgs.php',
    dataType: 'JSON',
    success: function( oData ) {
        $.each( oData, function( key, value ) {
            document.write( key + ': ' + value + '<br>' );
        });
    }

});

Comments

0

Try this code. This may help you

$json = '{"Fruit":"Apple","Veggies":"Carrot\r\nCelery\r\n\r\nCucumbers"}';
$json = json_decode($json,true);
array_walk($json, function(&$val){$val = html_entity_decode(nl2br($val));});
echo "<pre>";
print_r($json);
echo "</pre>";
exit;

Comments

0

use

$html = json_decode(nl2br($json,false),true);

Syntax: nl2br(string,xhtml)

With: xhtml Optional. A boolean value that indicates whether or not to use XHTML compatible line breaks:

TRUE- Default. Inserts <br />

FALSE - Inserts <br>

with <br /> it make json error.

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.