简体   繁体   中英

SimpleXML Parse data with same element name

I am trying to parse the Elements of this file that are named Roster->Player->Name

http://gamebattles.majorleaguegaming.com/ps4/call-of-duty-ghosts/team/ngx2-gaming/stats.xml

I have successfully pulled the other fields with the code below, but as you can see if you run the code, it will only show the first player name on Line 26. Can someone help me out how to display the other ones?

Thanks!

<?php
$url="http://gamebattles.majorleaguegaming.com/ps4/call-of-duty-ghosts/team/ngx2-gaming/stats.xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);    // get the url contents
$data = curl_exec($ch); // execute curl request
curl_close($ch);
$xml = simplexml_load_string($data);
?>
<html>
<head>
<title>Stats</title>
</head>
<body>
Game: <?php echo $xml->arena; ?><br/>
Platform: <?php echo $xml->platform; ?><br/>
Matches Played: <?php echo $xml->alltimeStats->matchesPlayed; ?><br/>
Shutotus: <?php echo $xml->currentStats->shutouts; ?><br/>
Level: <?php echo $xml->currentStats->level; ?><br/>
Current Streak: <?php echo $xml->currentStats->streak; ?><br/>
Ladder Place: <?php echo $xml->currentStats->place; ?><br/>
TeamName: <?php echo $xml->name; ?><br/>
Wins: <?php echo $xml->currentStats->wins; ?><br/>
Losses: <?php echo $xml->currentStats->losses; ?><br/>
Roster: <?php echo $xml->roster->player->name; ?><br/>
</body>
</html>

Since there are several siblings elements in the XML document, you have to loop over them, like you would an array :

<?php
foreach($xml->roster->player as $player) {
    echo $player->name; ?><br/><?php
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM