简体   繁体   English

将 JSON 数组中的换行符转换为换行符:JSON_decode 和 nl2br

[英]Converting Newlines in JSON array to line breaks: JSON_decode and nl2br

I cannot get the below array to replace the carriage return and newline with an HTML break <br />我无法获得以下数组以用 HTML 中断替换回车符和换行符<br />

JSON Array: JSON 数组:

{"Fruit":"Apple","Veggies":"Carrot\\r\\nCelery\\r\\n\\r\\nCucumbers"} {"水果":"苹果","蔬菜":"胡萝卜\\r\\n芹菜\\r\\n\\r\\n黄瓜"}

I'm trying this and having no luck:我正在尝试这个并且没有运气:

$html = json_decode(nl2br($json),true); $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'.换行符在 HTML 本身的源代码中可见,但是我无法获得<br />代码来替换“换行符”。

I've tried this suggestion as well and it did not work either: Replacing \\r\\n (newline characters) after running json_encode我也尝试过这个建议,但它也不起作用: 运行 json_encode 后替换 \\r\\n (换行符)

在 JSON 解码后运行nl2br() ,而不是在 JSON 数组源上运行。

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返回一个 JSON

Then use jQuery or your favorite library( even a custom build one ) to send an ajax request to the page.然后使用 jQuery 或您最喜欢的库(甚至是自定义构建库)向页面发送 ajax 请求。

$.ajax({

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

});

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;

use

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

Syntax: nl2br(string,xhtml)语法: nl2br(string,xhtml)

With: xhtml Optional.与: xhtml可选。 A boolean value that indicates whether or not to use XHTML compatible line breaks:一个布尔值,指示是否使用兼容 XHTML 的换行符:

TRUE - Default. TRUE - 默认。 Inserts <br />插入<br />

FALSE - Inserts <br> FALSE - 插入<br>

with <br /> it make json error.使用<br />它会使 json 错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM