douyouchou1085 2014-02-25 03:54
浏览 103
已采纳

使用PHP获取XML:如何从具有相同名称的2个节点获取属性

I am getting attributes from XML nodes and saving them to variables with a for loop as such:

for ($i = 0; $i < 10; $i++){
    $group = $xml->Competition->Round[0]->Event[$i][Group];
    if($group == "MTCH"){
        $eventid = $xml->Competition->Round[0]->Event[$i][EventID];
        $eventname = $xml->Competition->Round[0]->Event[$i][EventName];
        $teamaname = $xml->Competition->Round[0]->Event[$i]->EventSelections[0][EventSelectionName];
        $teambname = $xml->Competition->Round[0]->Event[$i]->EventSelections[1][EventSelectionName];
        echo "<br/>" . $eventid . ": " . $eventname . ", " .  $teamaname . "VS" . $teambname;
    }//IF
}//FOR

I can save each Event[EventID] and each Event[EventName] but I cannot get the EventSelections[EventSelectionNames] to save.

I am guessing this is because there are multiple (2) <EventSelection>s for each <Event>, this is why I tried to get them individually uising [0] and [1].

The part of the XML file in question looks like:

<Event EventID="1008782" EventName="Collingwood v Fremantle" Venue="" EventDate="2014-03-14T18:20:00" Group="MTCH">
  <Market Type="Head to Head" EachWayPlaces="0">
    <EventSelections BetSelectionID="88029974" EventSelectionName="Collingwood">
      <Bet Odds="2.10" Line=""/>
    </EventSelections>
    <EventSelections BetSelectionID="88029975" EventSelectionName="Fremantle">
      <Bet Odds="1.70" Line=""/>
    </EventSelections>
  </Market>
</Event>

Can anyone point me in the right direction to save the EventSelectionNames to variables?

  • 写回答

2条回答 默认 最新

  • duanjie9630 2014-02-25 14:23
    关注

    Rather than looping and checking for $group, use xpath to select data directly:

    $xml = simplexml_load_string($x); // assume XML in $x
    $group = $xml->xpath("/Event[@Group = 'MTCH']")[0];
    echo "ID: $group[EventID], name: $group[EventName]" . PHP_EOL;
    

    If there are always two <EventSelections>, you can:

    echo "Team A: " . $group->Market->EventSelections[0]['EventSelectionName']" . PHP_EOL;
    echo "Team B: " . $group->Market->EventSelections[1]['EventSelectionName']" . PHP_EOL;
    

    Otherwise, use foreach:

    foreach ($group->Market->EventSelections as $es)
        $teamnames[] = $es['EventSelectionName'];
    
    echo "There are " . count($teamnames) . "Teams:" . PHP_EOL;
    foreach ($teamname as $teamname) echo $teamname . PHP_EOL;
    

    see it in action: https://eval.in/105642

    Note:

    The [0] at the end of the code-line starting with $group = $xml->xpath...requires PHP >= 5.4. If you are on a lower version, update PHP or use:

    $group = $xml->xpath("/Event[@Group = 'MTCH']");
    $group = $group[0];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部