【问题标题】:Converting Newlines in JSON array to line breaks: JSON_decode and nl2br将 JSON 数组中的换行符转换为换行符:JSON_decode 和 nl2br
【发布时间】:2014-02-23 16:42:40
【问题描述】:

我无法获取下面的数组来用 HTML 中断 <br /> 替换回车符和换行符

JSON 数组:

{"水果":"苹果","蔬菜":"胡萝卜\r\n芹菜\r\n\r\n黄瓜"}

我正在尝试这个,但没有运气:

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

在 HTML 本身的源代码中可以看到换行符,但是我无法获得 <br /> 代码来替换“换行符”。

我也试过这个建议,但也没有用: Replacing \r\n (newline characters) after running json_encode

【问题讨论】:

  • 你是如何得到 json 的?我认为最好在进行 json 编码之前或之后替换,如果你没有编辑 json 的可能性

标签: php json nl2br


【解决方案1】:

使用

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

语法:nl2br(string,xhtml)

使用:xhtml 可选。一个布尔值,指示是否使用与 XHTML 兼容的换行符:

TRUE- 默认值。插入<br />

FALSE - 插入 <br>

<br /> 会导致 json 错误。

【讨论】:

    【解决方案2】:

    试试这个代码。这可能对你有帮助

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        也许你应该试试

        $arJson = array( 'fruit' => 'apple', 
                         'veggies' => array( 'carrot', 'celery', 'cucumbers' ) );
        
        header( 'Content-Type: application/json' );
        
        print json_encode( $arJson );
        

        返回 JSON

        然后使用 jQuery 或您喜欢的库(甚至是自定义构建库)向页面发送 ajax 请求。

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

        【讨论】:

          猜你喜欢
          • 2011-02-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-09
          • 2018-12-20
          • 1970-01-01
          • 2016-12-11
          相关资源
          最近更新 更多