我在检索具有命名空间的XML Feed的标记值时遇到了一些问题。
我已经阅读并尝试在之前的问题上实施一些建议的答案,但我仍然得到一个空数组,或者像
这样的警告Warning: SimpleXMLElement::xpath() [simplexmlelement.xpath]: Undefined namespace prefix
我看了Parse XML with Namespace using SimpleXML。
XML Feed数据如下所示:
<Session>
<AreComplimentariesAllowed>true</AreComplimentariesAllowed>
<Attributes xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d3p1:string>0000000009</d3p1:string>
<d3p1:string>0000000011</d3p1:string>
</Attributes>
</Session>
我目前的代码:
foreach($xml->Session as $event){
if(!empty($event->Attributes)){
foreach($event->xpath('//Attributes:d3p1') as $atts) {
echo $atts."<br />";
}
}
}
任何指导都将不胜感激。
感谢。
答案 0 :(得分:1)
您需要注册命名空间:
foreach ($xml->xpath('//Attributes') as $attr) {
$attr->registerXPathNamespace('ns',
'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
foreach ($attr->xpath('//ns:string') as $string) {
echo $string, PHP_EOL;
}
}
如果您只想获取string
标记的值:
$xml->registerXPathNamespace('ns',
'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
foreach ($xml->xpath('//Attributes/ns:string') as $string) {
echo $string, PHP_EOL;
}