Skip to content
Advertisement

Convert xml string to json in php

I have the fokllowing xml string that i’d like to convert to a json string.

Here is the xml in a variable:

$output = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://api-v1.gen.mm.vodafone.com/mminterface/request">
        <soapenv:Header/>
        <soapenv:Body>
            <req:ResponseMsg>
                <![CDATA[
                <?xml version="1.0" encoding="UTF-8"?><response xmlns="http://api-v1.gen.mm.vodafone.com/mminterface/response"><ResponseCode>100000014</ResponseCode><ResponseDesc>Missing mandatory parameter:OriginatorConversationId</ResponseDesc><ConversationID></ConversationID><OriginatorConversationID></OriginatorConversationID><ServiceStatus>0</ServiceStatus></response>]]>
            </req:ResponseMsg>
        </soapenv:Body>
    </soapenv:Envelope>';

Then I’m using this regex to convert it but it returns blank.

$pattern = "(<Response(.+)>[sS]*?</Response>)";
preg_match_all($pattern, $output, $matches);
$xml = simplexml_load_string($matches[0][0]);
echo json_encode($xml);

What am i missing?

Advertisement

Answer

You’ll find it a lot easier if you also process the outer SOAP document with SimpleXML, rather than trying to force it into a regex. It might look a bit complicated because of the namespaces, but it’s quite straightforward using the SimpleXML::children() method:

$soap = simplexml_load_string($output);

$response = $soap
    ->children('http://schemas.xmlsoap.org/soap/envelope/')
    ->Body
    ->children('http://api-v1.gen.mm.vodafone.com/mminterface/request')
    ->ResponseMsg;

$xml = simplexml_load_string(trim($response));

// ...

See https://3v4l.org/iQIAT for a full demo

(As an aside, using json_encode directly with a SimpleXML object can have a couple of strange side-effects, but should work ok with this document. You might find it more reliable to just extract the values you want using SimpleXML’s own API, e.g. $xml->ResponseCode)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement