SimpleXML:获取子节点

时间:2011-08-02 21:28:08

标签: php 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 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;
    }
?>

3 个答案:

答案 0 :(得分:6)

使用xpath

$ccc = $xml->xpath('aaa/bbb/ccc');
foreach($ccc as $c){
    echo (string)$c."<br/>";
}

结果:

Only this childnod what I need 
And this one 

此外,在您的初始尝试中,$bbb[3]没有意义,因为您只有三个项目,从索引0开始。

答案 1 :(得分:4)

更具动态性的解决方案

<?php
header('Content-type:text/html; charset=utf-8');
$xml = simplexml_load_file('2.xml');
    foreach ($xml->aaa as $aaa){
        if ($aaa->bbb) {
            foreach ($aaa->bbb as $bbb) {
                if ($bbb->ccc)
                    foreach ($bbb->ccc as $ccc) {
                        echo $ccc;
                    }
                }
            }
        }
    }
?> 

答案 2 :(得分:2)

我不知道如何使用simplexml的返回,但是从我的代码中看到的,这应该可行:

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