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

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)
doukun1450
doukun1450 然后你就完成了:)
接近 4 年之前 回复
duanran8648
duanran8648 实际上我是在编码一个数组,xml字符串存在于该数组中。
接近 4 年之前 回复

Actually I just found my answer by the hint of htmlentities @Álvaro González gave. I just converted my xml string like,

[
    'name' => 'xmlName',
    'xml'  => htmlentities($xml) 
]

I am able to receive the xml string as it is without any json break.

dsk88199
dsk88199 González,就像我在我的问题中所说的那样,我不得不从包含一个包含xml数据的列的数据库表中获取一行,并使用webservice将其保存到另一个数据库。 当我使用RestAPI客户端发布我的webservice时,它会返回我损坏的json。 我只是简单地使用slim来回复上面提到的响应。 当我用htmlentities()手动转换我的xml字符串时,它工作正常,我收到了很好的json。 我简单解码json并将其保存到另一个数据库表,这是我的问题。
接近 4 年之前 回复
duanaoshu1989
duanaoshu1989 您必须做其他未说过的事情(例如在浏览器中显示XML或使用某些库处理数据)。 这个网站是一个集体知识库,无论谁在谷歌搜索都会得到错误的印象,即json_encode()被破坏或不完整,当然不是这种情况。
接近 4 年之前 回复
doujiepin5547
doujiepin5547 它的工作正常我认为,如果我按原样传递$ xml,我的json就会中断。 这就是我使用htmlentities()的原因。 所以我的json没有得到休息,我不必撤消它。 我收到完全相同的字符串。
接近 4 年之前 回复
douyi8760
douyi8760 htmlentities()只会破坏您的XML(或者至少强制接收方撤消编码)。 为什么你认为你需要它?
接近 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐