使用Simple XML PHP解析SOAP响应

时间:2012-02-29 15:40:51

标签: php

使用simplexml传递SOAP响应后,我得到了以下输出。如何获得域的属性值,即名称和可用。

使用的代码:

 $xmlString = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $result);    
       $xml = simplexml_load_string($xmlString);
       print_r($xml);



SimpleXMLElement Object([soapBody] => SimpleXMLElement Object ([CheckAvailabilityResponse] => SimpleXMLElement Object([CheckAvailabilityResult] => &lt;?xml version="1.0" encoding="UTF-16"?&gt;
&lt;check&gt;
    &lt;domain name="MYNAMEISNIJIL.COM" avail="1" canBackorder="0"/&gt;
&lt;/check&gt;) ))

2 个答案:

答案 0 :(得分:3)

显然,你已经在返回中转义了XML(这是一个我现在忽略的坏习惯..)。另外,查看children()函数以使用命名空间而不是preg_replace ....忽略它,这对你有用:

  $outerxml = simplexml_load_string($xmlString);
  $innerxml = simplexml_load_string( htmlspecialchars_decode(
     $outerxml->soapBody->CheckAvailabilityResponse->CheckAvailabilityResult));

另一方面,我通常使用这个小工具来利用SOAPClient来解析肥皂回应:

//the soap way
class SneakyFauxSoap extends SoapClient {
    public $response;
    function __doRequest($val){
        return $this->response;
    }
}

$soap = new SneakyFauxSoap(null,
    array(
        'uri' =>'something',
        'location'=>'something',
        'soap_version' => SOAP_1_1));
$soap->response = $x;
var_dump($soap->somerandomfunction());

答案 1 :(得分:0)

受@ Wrikken的回答启发,我写了一个简单易用的类 使用PHP 5.3:

class SoapParser extends SoapClient {
  private $xml;

  function __construct($options) {
    $options['location'] = $options['uri'] = 'dummy';
    parent::__construct(null, $options);
  }

  public function __doRequest($request, $location, $action, $version,
                              $one_way = 0)
  {
    return $this->xml;
  }

  public function parse($xml) {
    $this->xml = $xml;
    return $this->dummyFunction();
  }
}

用法示例:

$soapParser = new SoapParser(array('soap_version' => 'SOAP_1_1'));
try {
  var_dump($soapParser->parse($response));
} catch (Exception $e) {
  die($e->getMessage());
}