SimpleXML: get child nodes

2019-01-28 10:59发布

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

标签: php simplexml
3条回答
▲ chillily
2楼-- · 2019-01-28 11:07

A more dynamic solution

<?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;
                    }
                }
            }
        }
    }
?> 
查看更多
Fickle 薄情
3楼-- · 2019-01-28 11:11

Use xpath

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

Result:

Only this childnod what I need 
And this one 

Also, in your initial attempt, $bbb[3] does not make sense because you have three items only, starting with index 0.

查看更多
看我几分像从前
4楼-- · 2019-01-28 11:27

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];
?> 
查看更多
登录 后发表回答