doubeng1278 2017-01-04 09:29
浏览 66

使用php slim在json对象中发送xml字符串

I have written a REST Api using slim framework 3, and returning response in JSON like this,

return $response->withHeader(
        'Content-type',
        'application/json; charset=utf-8'
    )->withJson($data, 200);

which is working fine.

$xml = '<?xml version="1.0" encoding="UTF-8"?><dialog createdBy=""createDate=""><dialog>' // looks like this

$data = [
    'name' => 'xmlName',
    'xml'  => $xml // fetching from db
]

Now, I have xml string stored in database and want to send it to the client end, I have to save that xml string as in another database as it is.

But when I encode xml string, my json gets break.

I have also tried like,

json_encode($data, JSON_HEX_TAG);

which converts my xml to.

"\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?\u003E
\u003Cdialog createdBy=\"\"

How can I correctly encode the xml in JSON and then get back the original xml string as it is?

Your feedback is much appreciated.

  • 写回答

2条回答 默认 最新

  • doupang1917 2017-01-04 09:50
    关注

    If you look at the withJson() source code you'll see that all it does with data is processing it with json_encode()—nothing special on the Slim side. In fact, your XML is just fine: \u003C and \u003E are the entities for < and >. Remember that JSON is a data format for computers, not people!

    Additionally, the JSON spec states that you need to have a top level object or array. So you can't just send a string back to the client and expect it to be processed as JSON because it will not be JSON. If json_encode() does not just crash it's because it has been designed to encode partial JSON since it's a useful feature some times. You absolutely need to design a valid JSON structure, e.g.:

    ->withJson(array($xml), 200)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?