使用simplexml

时间:2016-04-26 11:24:11

标签: php xml

在有人指出存在大量类似的类似问题之前,请记住,我已经尝试过用尽所有可以在堆叠中找到的方法。

我在使用simplexml从像这样结构的响应中提取出我想要的数据时遇到了麻烦。

<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>
  <authenticateresponse xmlns="http://somesite.co.nz">
    <authenticateresult>
      <username>Username</username>
      <token>XXXXXXXXX</token>
      <reference>
        <message>Access Denied</message>
      </reference>
    </authenticateresult>
  </authenticateresponse>
</soap:body>

在这种情况下,我想知道如何提取令牌和用户名。

1 个答案:

答案 0 :(得分:1)

您的XML具有在authenticateresponse元素声明的默认命名空间:

xmlns="http://somesite.co.nz"

请注意,声明default namespace的元素以及不带前缀的后代元素位于同一名称空间中。要访问默认命名空间中的元素,您需要将前缀映射到命名空间URI并在XPath中使用前缀,例如:

$raw = <<<XML
<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>
  <authenticateresponse xmlns="http://somesite.co.nz">
    <authenticateresult>
      <username>Username</username>
      <token>XXXXXXXXX</token>
      <reference>
        <message>Access Denied</message>
      </reference>
    </authenticateresult>
  </authenticateresponse>
</soap:body>
</soap:envelope>
XML;
$xml = new SimpleXMLElement($raw);
$xml->registerXPathNamespace('d', 'http://somesite.co.nz');
$username = $xml->xpath('//d:username');
echo $username[0];

<强> eval.in demo

输出

Username

一些以前的相关问题: