在有人指出有大量类似的问题之前,请记住,我已经尝试并用尽了我在这里可以找到的所有方法堆叠。
我在使用 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>
在这种情况下,我想知道如何提取令牌和用户名。
您的 XML 在 authenticateresponse
元素中声明了默认命名空间:
xmlns="http://somesite.co.nz"
请注意,声明默认命名空间的元素以及不带前缀的后代元素位于同一命名空间中。要访问默认命名空间中的元素,您需要将前缀映射到命名空间 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
以前的一些相关问题:
- 使用 PHP 的 simpleXML 解析 XML
- SimpleXML 中的 XPath 用于不需要前缀的默认命名空间