Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

<?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;
    }
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...