Xi Vix Xi Vix - 6 months ago 47
PHP Question

how to extract SOAP response in PHP

I have a SOAP response as follows:

<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope" xmlns="">
<faultcode>stuff</faultcode>
<faultstring>stuff</faultstring>
<detail>
<ns2:Exception xmlns:ns2="http://blah.com/">
<message>stuff</message>
</ns2:Exception>
</detail>
</S:Fault>
</S:Body>
</S:Envelope>


I need to extract faultcode, faultstring, and message.

I have tried SimpleXML_load_string, SimpleXMLElement, DOMDocument, registerXPathNamespace and json_decode but can't seem to get the exact procedure correct because I get errors instead of results. Thanks in advance.
Latest attempt:

$xmle1 = SimpleXML_load_string(curl_exec($ch));
if (curl_errno($ch)) {
print "curl error: [" . curl_error($ch) . "]";
} else {
$xmle1->registerXPathNamespace('thing1', 'http://blah.com/');
foreach ($xml->xpath('//thing1:message') as $item) {
echo (string) $item;
}

Answer
<?php
$string = <<<XML
<?xml version="1.0" ?>
<S:Envelope
    xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <S:Fault
            xmlns:ns4="http://www.w3.org/2003/05/soap-envelope"
            xmlns="">
            <faultcode>stuff</faultcode>
            <faultstring>stuff</faultstring>
            <detail>
                <ns2:Exception
                    xmlns:ns2="http://blah.com/">
                    <message>stuff</message>
                </ns2:Exception>
            </detail>
        </S:Fault>
    </S:Body>
</S:Envelope>
XML;

$_DomObject = new DOMDocument;
$_DomObject->loadXML($string);
if (!$_DomObject) {
    echo 'Error while parsing the document';
    exit;
}

$s = simplexml_import_dom($_DomObject);

foreach(['faultcode','faultstring','message'] as $tag){
        echo $tag.' => '.$_DomObject->getElementsByTagName($tag)[0]->textContent.'<br/>';
}

?>

outputs

faultcode => stuff
faultstring => stuff
message => stuff

you might want to write a class to parse the XML string and builk an nice Fault object with methods for easier access after you parse it.

Comments