使用PHP解析soap响应

时间:2013-09-30 20:50:30

标签: php xml parsing soap simplexml

我试图从下面的soap响应中获取所有元素和值作为数组。但我只是获取元素而没有价值观。

我使用此解析器来获取元素和值。提前谢谢。

这是我正在使用的代码,

  $response = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <toy:SearchReq xmlns:toy="www.something.com/toy" xmlns:gen="www.something.com/gen">
         <gen: manufacturedIn="SomePlace"/>
         <toy:SearchToy>
            <toy:SearchType>
               <gen:Shop Code="WALMART"/>
            </toy:SearchType>    
         </toy:SearchToy>
         <toy:SearchToy>
            <toy:SearchType>
               <gen:Shop Code="AMAZON"/>
            </toy:SearchType>    
         </toy:SearchToy>
      </toy:SearchReq>
   </soapenv:Body>
</soapenv:Envelope>';

$doc = simplexml_load_string($response);

$path = array($doc
    ->children('http://schemas.xmlsoap.org/soap/envelope/')
    ->Body
    ->children('www.something.com/toy'));


foreach($path as $elem){
    print_r($elem);
    $elemChild = $elem->children('www.something.com/gen');
    var_dump($elemChild);
}

2 个答案:

答案 0 :(得分:0)

您可以通过注册命名空间来读取SOAP消息 - 如果您关心消息的SOAP部分,则只需要命名空间位。

$xml = simplexml_load_string($xml);
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
foreach ($xml->xpath('//toy') as $toy)
{
    print_r($toy);
}

答案 1 :(得分:0)

请参阅此处的完整参考:https://stackoverflow.com/a/38783380/6511851

$sxe = new SimpleXMLElement($response); //in $response variable it's an XML file or response
$sxe->registerXPathNamespace('d', 'urn:schemas-microsoft-com:xml-diffgram-v1');
$result = $sxe->xpath("//NewDataSet");

echo "<pre>";
foreach ($result[0] as $title) {
    print_r($title);
}

有关详细信息,请访问网站:https://vaja906programmingworld.wordpress.com/