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

使用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>
  • 写回答

3条回答 默认 最新

  • dqp21271 2019-05-10 09:20
    关注

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

    <?php
    $data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
    echo json_encode($data, JSON_PRETTY_PRINT);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵