Reputation: 11
I need for my project echo xml data from xml
I use simplexml_load_file
I have
<group>
<admin>
<id>605</id>
</admin>
<members>
<id>2154</id>
<id>2256</id>
<id>3179</id>
</menbers>
</group>
<group>
<admin>
....
</admin>
<members>
...
...
</members>
</group>
My code is
$soubor="platebniudaje.xml";
$xml = simplexml_load_file($soubor);
foreach ($xml->group as $group) {
echo $group->admin->id . "<br>";
foreach ($group->members as $members) {
echo $members->id . "<br>";
}
}
My output is
605
2154
but i need
605
2154
2256
3179
Can you help me? Where is mistake?
Upvotes: 1
Views: 59
Reputation: 163217
You can have one or more id's so you can loop those as well.
Note that there is a type in the xml </menbers>
foreach ($xml->group as $group) {
echo $group->admin->id . PHP_EOL;
foreach ($group->members as $member) {
foreach($member->id as $id)
echo $id . PHP_EOL;
}
}
Or the shorter version if members occurs only once as pointed out by @Nigel Ren
foreach ($xml->group as $group) {
echo $group->admin->id . PHP_EOL;
foreach ($group->members->id as $id)
echo $id . PHP_EOL;
}
Output
605
2154
2256
3179
Upvotes: 0
Reputation: 24930
I'm not sure this is what your are looking for, but based only on the xml snippet in your question, this:
foreach($xml->xpath('//group//id') as $node) {
echo $node, PHP_EOL;
}
should output:
605
2154
2256
3179
Upvotes: 1