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)
    
    评论

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?