使用Simple XML解析SOAP响应PHP
问题描述:
使用simplexml传递SOAP响应之后,我得到了以下输出。我怎样才能得到域的属性值,即名称和效用。使用使用Simple XML解析SOAP响应PHP
代码:在返回
$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] => <?xml version="1.0" encoding="UTF-16"?>
<check>
<domain name="MYNAMEISNIJIL.COM" avail="1" canBackorder="0"/>
</check>)))
答
显然,你已经逃脱XML(这是一个不好的做法,我会忽略现在..)。此外,寻找到children()
函数的命名空间,而不是你preg_replace
工作....忽略了,这会为你工作:
$outerxml = simplexml_load_string($xmlString);
$innerxml = simplexml_load_string(htmlspecialchars_decode(
$outerxml->soapBody->CheckAvailabilityResponse->CheckAvailabilityResult));
在一个侧面说明,我通常使用这个珍闻利用SOAPClient
解析SOAP响应:
//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());
答
通过@ 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());
}
+1对于丑陋而又巧妙的SneakyFauxSoap hack :) – Sergio 2012-10-31 13:46:22