使用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.

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)

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.