How to parse SOAP response without SoapClient

后端 未结 2 1871
渐次进展
渐次进展 2020-12-03 09:35

I have spent the last few days trying to parse a SOAP response but I can\'t get it to work. I would like to be able to get all the \"oproduct\" objects.

EDIT: I am d

相关标签:
2条回答
  • 2020-12-03 09:45

    PHP comes with a SOAP client that should make it so you don't have to manually parse SOAP XML. See here: http://php.net/manual/en/book.soap.php

    Edit: For clarity, the SOAP client is not part of PHP, rather an extension.

    0 讨论(0)
  • 2020-12-03 09:51

    Could you clarify which version of PHP you're using (4 or 5)? Also is there a particular reason why you don't want to/can't use PHP 5's SOAP extension? Knowing this information should help us to give you a better answer.

    The reason the code sample above isn't working is that you're looking in the wrong namespace for the oproduct nodes. While the root node is contained in the SOAP namespace the oproduct ones are under the "http://v3.core.com.productserve.com/" namespace. You also need to use the namespace alias in the XPath query. Try this, although I haven't tested it:

    $xml = simplexml_load_string($response);
    $xml->registerXPathNamespace('ns', 'http://v3.core.com.productserve.com/');
    foreach ($xml->xpath('//ns:oproduct') as $item)
    {
      // do something
    }
    

    Hopefully that will solve your immediate problem.

    EDIT Thanks for the clarification. Again, untested but maybe this would work:

    $xml = simplexml_load_string($response);
    $xml->registerXPathNamespace('soapenv', 'http://schemas.xmlsoap.org/soap/envelope/');
    $xml->registerXPathNamespace('ns', 'http://v3.core.com.productserve.com/');
    foreach ($xml->xpath('/soapenv:envelope/soapenv:body/ns:getproductlistresponse/ns:oproduct') as $item)
        {
          // do something
        }
    

    Perhaps you need to go from the root node to the soap-Env:body to the oproduct nodes in the query. Hopefully that will work.

    Further edit: I think I've just cracked this. Try the following code:

    $xml = simplexml_load_string($response);
    $ns = $xml->getNamespaces(true);
    $soap = $xml->children($ns['soap-env']);
    $getproductlistresponse = $soap->body->children($ns['ns1']);
    foreach ($getproductlistresponse->children() as $item)
    {
      //This example just accesses the iid node but the others are all available.
      echo (string) $item->iid . '<br />';
    }
    

    Not the prettiest code but it works. I was hoping to get this to work with an XPath query but it was beyond my rudimentary knowledge of XPath. Perhaps someone else can post an answer using XPath?

    0 讨论(0)
提交回复
热议问题