2019-05-10 09:16
浏览 573

使用json_encode()时如何添加空格和换行? [重复]

This question already has an answer here:

I've seen multiple answers in here but none of them had a solution to my question, so I made an account to ask this question. I understand now that is not an allowed character in json because the backslash is not allowed and that's why the problem is occurring.

I have the following code to encode an array in json:

$data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
echo json_encode($data);

I'm trying to have the string outputted as follows:


"test1": "something1",

"test2": "something2",

"test3": "something3"


But what I'm getting is this:


This is my go at it:

$data = array('test1' => 'something1
', 'test2' => 'something2
', 'test3' => 'something3
echo json_encode($data);

but this returns

{"test1":"something1 ","test2":"something2 ","test3":"something3 "}


图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 这里有一个答案:

  • 使用PHP漂亮打印JSON 22 answers < / li>

    我在这里看到了多个答案,但他们都没有解决我的问题,所以我创建了一个帐户 问这个问题。 我现在明白 不是json中允许的字符,因为不允许使用反斜杠,这就是问题发生的原因。

    我有以下代码 在json中编码数组:

     $ data = array('test1'=&gt;'something1','test2'=&gt;'something2  ','test3'=&gt;'something3'); 
    echo json_encode($ data); 




    “test2” :“something2”,


    } < 但是我得到的是:

    {“test1”:“something1”,“test2”:“something2”,“test3”:“something3 “}


     $ data = array  ('test1'=&gt;'something1 
    echo json_encode($ data); 


    {“test1”:“something1 ”,“test2”:“something2 ”,“test3”:“something3 ”}

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dqp21271 2019-05-10 09:20

    You can add a second parameter to json_encode. This is called the JSON_PRETTY_PRINT constant:

    $data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
    echo json_encode($data, JSON_PRETTY_PRINT);
    打赏 评论
  • dtwkt46424 2019-05-10 09:23

    You can use JSON_PRETTY_PRINT with header

    $data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data,JSON_PRETTY_PRINT);


    $json= json_encode($data,JSON_PRETTY_PRINT);
    printf("<pre>%s</pre>", $json);
    打赏 评论
  • dongposhi8677 2019-05-10 09:24

    JSON is an interchange format, so you need not be concerned about the looks very much.

    Anyway, you can use flag constants to alter the encoding process

    $a = '{"test1":"something1","test2":"something2","test3":"something3"}';
    print_r(json_encode(json_decode($a, true), JSON_PRETTY_PRINT));

    See live example: https://3v4l.org/CEc3L

    打赏 评论

相关推荐 更多相似问题