Dirty Bird Design
Dirty Bird Design

Reputation: 5553

How to parse returned XML from SOAP request - jQuery

I haven't dealt with xml in this format before, w/no tag name. There may be more or less nodes returned, so I can't count them. There may be one or two after, so I can't count from end. I need to find the who's value is result. From there find the 's text.

The returned data is this:

<pre><?xml version="1.0" encoding="utf-8"?>
    <soapenv:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
    <ns1:demosetupResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://tempuri.org/">
    <demosetupReturn xmlns:ns2="http://xml.apache.org/xml-soap" xsi:type="ns2:Map">
    <item xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
      <key xsi:type="soapenc:string">DemoUName</key>
      <value xsi:type="soapenc:string"></value>
    </item>
    <item xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
      <key xsi:type="soapenc:string">DemoPass</key>
      <value xsi:type="soapenc:string"></value>
    </item>
    <item xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
      <key xsi:type="soapenc:string">FutAcct</key>
      <value xsi:type="soapenc:string"></value>
    </item>
    <item xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
      <key xsi:type="soapenc:string">FxAcct</key>
      <value xsi:type="soapenc:string"></value>
    </item>
    <item xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
      <key xsi:type="soapenc:string">UUID</key>
      <value xsi:type="soapenc:string"></value>
    </item>
    <item xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
      <key xsi:type="soapenc:string">Result</key>
      <value xsi:type="soapenc:string">Error: Duplicate user account!</value>
    </item>
  </demosetupReturn>
</ns1:demosetupResponse>

Relevant part of my PHP cURL script:

f(curl_exec($soap_do) === false) {
        $err = 'Curl error: ' . curl_error($soap_do);
        curl_close($soap_do);
        print $err;
    } else {
        $result = curl_exec($soap_do);
        echo '<pre>';
        print_r($result);
        // print_r($xml_post_string);
    }
    curl_close($soap_do);

Upvotes: 0

Views: 67

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

You can use XPath to extract the main body of the SOAP message ( I think in this case it is the <demosetupReturn xml... element. And then use SimpleXML to iterate over the <item> elements and create an output array of the key/value pairs.

$xml = simplexml_load_string($result);
$body = $xml->xpath("//soapenv:Body//demosetupReturn")[0];
$output = [];
foreach ( $body as $item)  {
    $output[(string)$item->key] = (string)$item->value;
}
print_r($output);

Upvotes: 1

Related Questions