【问题标题】:JSON_PRETTY_PRINT not working as expected when Content-Type is HTML当 Content-Type 为 HTML 时,JSON_PRETTY_PRINT 无法按预期工作
【发布时间】:2013-11-30 16:35:01
【问题描述】:

我正在动态接收 JSON 字符串,如下所示:

{ "post": [ { "id": "11", "body": "", "image": "images/rose.png", "stamp": "2013-11-04 14:50 :11" } ] }

我正在尝试按如下方式漂亮地打印这个 JSON 字符串:

{
    "post": [
        {
            "id": "11",
            "body": "",
            "image": "images/rose.png",
            "stamp": "2013-11-04 14:50:11"
        }
    ]
}

所以,我尝试了以下代码(仅用于演示目的):

<?php

$str = '{ "post": [ { "id": "11", "body": "", "image": "images\/rose.png", "stamp": "2013-11-04 14:50:11" } ] }';
$obj = json_decode($str);
echo json_encode($obj, JSON_PRETTY_PRINT);

它只是输出未格式化的 JSON 字符串:

{ "post": [ { "id": "11", "body": "", "image": "images/rose.png", "stamp": "2013-11-04 14:50 :11" } ] }

但是当我在json_encode() 语句上方添加以下行时,它按预期工作。

header('Content-Type: text/plain');

什么可能导致此问题?当Content-Typetext/html 时为什么它不起作用?

【问题讨论】:

    标签: php mysql sql json


    【解决方案1】:

    JSON_PRETTY_PRINT 使用空格来格式化 JSON。当它显示为 HTML 时,空白将被忽略。如果要保留格式,请将 JSON 包装在 &lt;pre&gt; 标记中。

    例如:

    <?php
    
    $str = '{ "post": [ { "id": "11", "body": "", "image": "images\/rose.png", "stamp": "2013-11-04 14:50:11" } ] }';
    $obj = json_decode($str);
    $json = json_encode($obj, JSON_PRETTY_PRINT);
    
    printf("<pre>%s</pre>", $json);
    

    如果您不想使用 &lt;pre&gt; 标签,那么您也可以在 JSON 包含的任何元素上使用 CSS 属性 white-space: pre

    【讨论】:

      【解决方案2】:

      你使用这个标题:

      header('Content-Type: application/json; charset=utf-8');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-24
        • 1970-01-01
        • 1970-01-01
        • 2013-12-23
        • 2014-12-09
        • 2016-01-13
        • 2020-09-21
        • 2011-08-17
        相关资源
        最近更新 更多