使用php [也许2个foreach循环]解析复杂的xml?

时间:2015-06-12 14:23:57

标签: php xml parsing

<Lineups date="2015-06-11">
<Game start_time="2015-06-11 09:10:00" number="901" revised="false">
<Team number="901" name="San Diego">
<Player name="Wil Myers" position="CF"/>
<Player name="Will Venable" position="LF"/>
<Player name="Matt Kemp" position="RF"/>
<Player name="Yonder Alonso" position="1B"/>
<Player name="Derek Norris" position="C"/>
<Player name="Cory Spangenberg" position="2B"/>
<Player name="Will Middlebrooks" position="3B"/>
<Player name="Alexi Amarista" position="SS"/>
<Player name="Andrew Cashner" position="P"/>
</Team>
</Game>
</Lineups>

我有这个xml文件,我想在php中解析它,所以我可以在网站上显示它。

有多个游戏,每个团队都有多个玩家。我是否必须在另一个foreach循环中使用foreach循环?

我想要显示如下内容:

  

游戏[0]开始时间
  姓名团队[0]   播放器[0]   播放器[1]   播放器[2]   ...   姓名团队[1]

     

游戏[1]开始时间
  姓名团队[0]
  播放器[0]
  ...

有些人可以更熟练地开始我应该如何启动我的php代码来解析这个xml文件?

1 个答案:

答案 0 :(得分:1)

以某种方式使用simplexml

$str = '<Lineups date="2015-06-11">
<Game start_time="2015-06-11 09:10:00" number="901" revised="false">
<Team number="901" name="San Diego">
<Player name="Wil Myers" position="CF"/>
<Player name="Will Venable" position="LF"/>
<Player name="Matt Kemp" position="RF"/>
<Player name="Yonder Alonso" position="1B"/>
<Player name="Derek Norris" position="C"/>
<Player name="Cory Spangenberg" position="2B"/>
<Player name="Will Middlebrooks" position="3B"/>
<Player name="Alexi Amarista" position="SS"/>
<Player name="Andrew Cashner" position="P"/>
</Team>
</Game>
</Lineups>';

$xml = simplexml_load_string($str);

foreach ($xml->Game as $game) {
   echo "Game number " . $game['number'] . " start_time " . $game['start_time'] . "\n"; 
   foreach($game->Team as $team) {
     echo "  Team " . $team['name'] . " number " . $team['number'] . "\n";
     $players = array();
     foreach($team->Player as $player) $players[]  = $player['name'] . " ";  
     echo "    " . implode(", ", $players) . "\n"; 
   }
 } 

结果

Game number 901 start_time 2015-06-11 09:10:00
  Team San Diego number 901
    Wil Myers , Will Venable , Matt Kemp , Yonder Alonso , Derek Norris , Cory Spangenberg , Will Middlebrooks , Alexi Amarista , Andrew Cashner