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

使用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条)

报告相同问题?

悬赏问题

  • ¥100 微信小程序跑脚本授权的问题
  • ¥60 为什么使用python对地震数据进行umap降维后,数据成图会出现不连续的现象
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?