我在下面给出了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 );
答案 0 :(得分:2)
您可能希望使用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];
}
答案 1 :(得分:0)
如果要使用SimpleXML,则必须使用名称空间和children
方法:
echo (string) $xml->children("http://schemas.xmlsoap.org/soap/envelope/")
->Body
->children()
->addItemToShoppingCartResponse
->ack;
输出:
Warning