2019-05-10 09:16
浏览 912

使用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条回答 默认 最新

相关推荐 更多相似问题