Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用simplexml后访问XML时出现问题_Php_Xml - Fatal编程技术网

Php 使用simplexml后访问XML时出现问题

Php 使用simplexml后访问XML时出现问题,php,xml,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"&g

在有人指出有很多类似的问题之前,请记住,我已经尝试并用尽了所有我能在这里找到的方法

我在使用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>

用户名
XXXXXXXXX
拒绝访问

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

您的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];
以前的几个相关问题:


很可能是默认名称空间(
xmlns=)http://somesite.co.nz“
)会导致问题。瑞德:谢谢你。我正在复习其他一些问题。出于某些奇怪的原因,即使我完全按照您所做的方式重写代码,但仍然失败,我的用户名上有一个未定义的偏移量。您能否发布简短的演示,可能是在eval.in中,以重现问题?否则我不知道…当我静态地写它时,你的解决方案是有效的,错误必须在某个地方的响应数据中,我只在这里发布了一小部分。谢谢你的帮助,非常感谢@哈
Username