dsxd62219570
2019-05-10 09:16
浏览 957
已采纳

使用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:

<?php
$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:

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

This is my go at it:

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

but this returns

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

</div>

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

此问题已经存在 这里有一个答案:</ p>

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

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

    我有以下代码 在json中编码数组:</ p>

     &lt;?php 
     $ data = array('test1'=&gt;'something1','test2'=&gt;'something2  ','test3'=&gt;'something3'); 
    echo json_encode($ data); 
     </ code> </ pre> 
     
     

    我正在尝试输出如下字符串: </ p>

    {</ p>

    “test1”:“something1”,</ p>

    “test2” :“something2”,</ p>

    “test3”:“something3”</ p>

    } </ p> </ blockquote> < 但是我得到的是:</ p>

    {“test1”:“something1”,“test2”:“something2”,“test3”:“something3 “} </ p> </ blockquote>

    这是我的目标:</ p>

     &lt;?php 
     $ data = array  ('test1'=&gt;'something1 
    ','test2'=&gt;'something2 
    ','test3'=&gt;'something3 
    '); 
    echo json_encode($ data); 
     </  code> </ pre> 
     
     

    但是返回</ p> <block 引用>

    {“test1”:“something1 ”,“test2”:“something2 ”,“test3”:“something3 ”} </ p> </ blockquote> </ DIV>

3条回答 默认 最新

相关推荐 更多相似问题