SimpleXML解析具有相同元素名称的数据

时间:2014-01-22 23:18:18

标签: php xml

我正在尝试解析名为Roster-> Player-> Name

的此文件的元素

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

我已经使用下面的代码成功拉出了其他字段,但正如您所看到的,如果您运行代码,它将只显示第26行的第一个玩家名称。有人可以帮助我显示其他的吗?

谢谢!

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

1 个答案:

答案 0 :(得分:1)

由于XML文档中有多个兄弟元素,因此必须循环遍历它们,就像使用数组一样:

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