SimpleXML:获取子节点 [英] SimpleXML: get child nodes

查看:68
本文介绍了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.我不知道如何获得这两个子节点.

I want parse the XML as given above with PHP. I don't know how to get these two child nodes.

当我使用下面的代码时,它会触发错误:Warning: main() [function.main]: Cannot add element bbb number 2 when only 0 such elements exist in

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;
    }
?>

推荐答案

我不知道如何使用simplexml的返回值,但是根据我从您的代码中看到的内容,这应该可以工作:

I don't know how to use the return of simplexml, but from what I have seen from your code, this should work:

<?php
header('Content-type:text/html; charset=utf-8');
$xml = simplexml_load_file('2.xml');
echo $xml->aaa[2]->bbb[2]->ccc[0];
echo $xml->aaa[2]->bbb[2]->ccc[1];
?> 

这篇关于SimpleXML:获取子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆