努力用SimpleXML读取节点

时间:2012-09-03 11:18:39

标签: php xml simplexml

以下是来自API的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>
    <GetCertificateResponse xmlns="http://url.com">
      <GetCertificateResult>
        <ReturnValue xmlns="">
          <Status>Success</Status>
          <Message/>
          <CertificateNumber/>
          <URL/>
        </ReturnValue>
      </GetCertificateResult>
    </GetCertificateResponse>
  </soap:Body>
</soap:Envelope>

如何重新获取状态节点?我尝试了很多组合:

            $getCertificateXMLResponse = simplexml_load_string($getCertificateXMLResponse);

        echo  $getCertificateXMLResponse->GetCertificateResponse->GetCertificateResult->ReturnValue->Status;

2 个答案:

答案 0 :(得分:1)

你也可以用Xpath

来做
$xml = simplexml_load_string($soap, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');

$result = $xml->xpath('//Status');
echo $result[0];

答案 1 :(得分:0)

它......丑陋......但是工作

$xml = new SimpleXMLElement(file_get_contents('a.xml'),0,false,'');
$namespaces = $xml->getDocNamespaces(true);
$xml->registerXPathNamespace('empty', $namespaces['']);
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$status = array_shift($xml->xpath("soap:Body/empty:GetCertificateResponse/empty:GetCertificateResult/ReturnValue/Status"));
echo $status->asXML();

我很想看到更优雅的解决方案。

确实看了nusoap之类的内容。