0

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(.+)>[\s\S]*?<\/Response>)";
preg_match_all($pattern, $output, $matches);
$xml = simplexml_load_string($matches[0][0]);
echo json_encode($xml);

What am i missing?

1
  • Your pattern is not a valid regular expression pattern. $matches[0][0] is empty Commented Feb 8, 2021 at 12:14

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.