SimpleXML:获取子节点
<?xml version="1.0" encoding="utf-8" ?>
<items>
<aaa>
</aaa>
<aaa>
</aaa>
<aaa>
<bbb>
</bbb>
<bbb>
</bbb>
<bbb>
<ccc>
Only this childnod what I need
</ccc>
<ccc>
And this one
</ccc>
</bbb>
</aaa>
</items>
我想用 PHP 解析上面给出的 XML。我不知道如何获取这两个子节点。
当我使用下面的代码时,它会触发错误: Warning: main() [function.main]: Cannot add element bbb number 2 when only 0 such elements contains in
<?php
header('Content-type:text/html; charset=utf-8');
$xml = simplexml_load_file('2.xml');
foreach ($xml->aaa[2]->bbb as $bbb){
echo $bbb[2]->$ccc; // wrong in here
echo $bbb[3]->$ccc;
}
?>
<?xml version="1.0" encoding="utf-8" ?>
<items>
<aaa>
</aaa>
<aaa>
</aaa>
<aaa>
<bbb>
</bbb>
<bbb>
</bbb>
<bbb>
<ccc>
Only this childnod what I need
</ccc>
<ccc>
And this one
</ccc>
</bbb>
</aaa>
</items>
I want parse the XML as given above with PHP. I don't know how to get these two child nodes.
When I use the code below, it triggers the error: Warning: main() [function.main]: Cannot add element bbb number 2 when only 0 such elements exist in
<?php
header('Content-type:text/html; charset=utf-8');
$xml = simplexml_load_file('2.xml');
foreach ($xml->aaa[2]->bbb as $bbb){
echo $bbb[2]->$ccc; // wrong in here
echo $bbb[3]->$ccc;
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 xpath
结果:
另外,在您最初的尝试中,
$bbb[ 3]
没有意义,因为您只有三个项目,从索引 0 开始。Use xpath
Result:
Also, in your initial attempt,
$bbb[3]
does not make sense because you have three items only, starting with index 0.我不知道如何使用 simplexml 的返回,但从我从你的代码中看到的,这应该有效:
I don't know how to use the return of simplexml, but from what I have seen from your code, this should work:
更动态的解决方案
A more dynamic solution