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

报告相同问题?

悬赏问题

  • ¥30 matlab解优化问题代码
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline