我正在尝试获取faultstring
元素的内容,并且我对SimpleXML的对象语法($xml->...->faultstring
更加满意。)下面的DomDocument方法可以工作,但是我还是喜欢坚持使用SimpleXML。
PHP版本5.6.40,Libxml 2.9.1。
$xmlResponse = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Server did not recognize the value of HTTP Header SOAPAction: https://gw1.domain.com:4430/.</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>';
// DOES NOT WORK
$xml = simplexml_load_string($xmlResponse,NULL,NULL,"http://schemas.xmlsoap.org/soap/envelope/");
$faultstring = (string) ($xml->Body->Fault->faultstring);
var_dump($faultstring);
// WORKS
$_DomObject = new DOMDocument;
$_DomObject->loadXML($xmlResponse);
if (!$_DomObject) die("Error while parsing the document");
$s = simplexml_import_dom($_DomObject);
foreach(['faultcode','faultstring','detail'] as $tag) {
echo $tag.' => '.$_DomObject->getElementsByTagName($tag)[0]->textContent.'<br/>';
}
答案 0 :(得分:1)
<?php
$xmlResponse = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Server did not recognize the value of HTTP Header SOAPAction: https://gw1.domain.com:4430/.</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
XML;
XML名称空间正在逐渐成为障碍。它们是元素名称上的soap:
前缀。可以注册所有名称空间并使它以这种方式工作,但是仅使用XPath更容易:
$xml = new SimpleXMLElement($xmlResponse);
$fault = $xml->xpath("//faultstring");
echo (string)$fault[0] . "\n";
这是使用命名空间的外观。您仍然可以获得对象语法,但是它变得更加复杂。
$xml = new SimpleXMLElement($xmlResponse);
$fault = $xml->children("soap", true)->Body->children("soap", true)->Fault->children()->faultstring;
echo (string)$fault . "\n";
两者的输出:
Server did not recognize the value of HTTP Header SOAPAction: https://gw1.domain.com:4430/.