如何在php中读取soapenv:Envelope xml节点?

曼尼什·马尔维娅(Manish Malviya)

我在下面给出了xml数据文件。我想阅读节点。谁能帮我吗。

$this->soapResponse 

具有响应xml数据。

 <?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<addItemToShoppingCartResponse xmlns="http://www.sample.com/services">
<ack>Warning</ack>
</addItemToShoppingCartResponse>
</soapenv:Body>
</soapenv:Envelope>

我在尝试

$xml = new  SimpleXMLElement($this->soapResponse);
print_r((string)$xml->addItemToShoppingCartResponse->ack );
延斯·科克(Jens A. Koch)

您可能要使用simplexml_load_string(),然后向那里注册您的名称空间,registerXPathNamespace()然后可以使用来开始处理您的项目xpath()然后,您可以使用这些命名空间在xpath查询中正确处理各项。

<?php

$xml = '
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<addItemToShoppingCartResponse xmlns="http://www.sample.com/services">
    <ack>Warning</ack>
</addItemToShoppingCartResponse>
</soapenv:Body>
</soapenv:Envelope>
';

$xml = simplexml_load_string($xml, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");

// register your used namespace prefixes
$xml->registerXPathNamespace('soap-env', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('services', 'http://www.sample.com/services'); // ? ns not in use

// then use xpath to adress the item you want (using this NS)
$nodes = $xml->xpath('/soapenv:Envelope/soapenv:Body/services:addItemToShoppingCartResponse/services:ack');
$ack = (string) $nodes[0];
var_dump($ack);

来自评论的问题

“如果我的文件在addItemToShoppingCartResponse节点中有子节点怎么办?如何申请foreach循环?”

回答

使用xpath进行旅行并选择节点,该节点在项目上方一层。这里是“船”。您将在船下获得所有物品。然后可以使用foreach迭代来获取内容。

注意:节点始终是“列表/数组”-因此,您需要[0]但是,您也可以在使用时看到它var_dump()

// example data looks like this
// addItemToShoppingCartResponse -> ship -> item
$xml = '
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<addItemToShoppingCartResponse xmlns="http://www.sample.com/services">
   <ack>warrning</ack> 
   <ship>
     <item>231</item>
     <item>232</item>
   </ship>
</addItemToShoppingCartResponse>
</soapenv:Body>
</soapenv:Envelope>
';

// load xml like above + register NS

// select items node (addItemToShoppingCartResponse -> ship)
$items = $xml->xpath('/soapenv:Envelope/soapenv:Body/services:addItemToShoppingCartResponse/services:ship/services:item');

// iterate item nodes
foreach ($items as $item) 
{
  //var_dump($item);
  echo (string) $item[0];
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章