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

时间:2014-02-25 11:54:55

标签: php xml

我从XML节点获取属性并使用for循环将它们保存到变量中:

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

我可以保存每个Event[EventID]和每个Event[EventName],但我无法保存EventSelections[EventSelectionNames]

我猜这是因为每个<EventSelection>s有多个(2)<Event>,这就是我尝试单独使用[0][1]的原因。

有问题的XML文件部分如下:

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

有人能指出我正确的方向将EventSelectionName保存到变量吗?

2 个答案:

答案 0 :(得分:1)

使用$group直接选择数据,而不是循环和检查xpath

$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;

如果总是两个<EventSelections>,您可以:

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

否则,请使用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;

在行动中看到它:https://eval.in/105642

注意

[0]开头的代码行末尾的$group = $xml->xpath...需要PHP&gt; = 5.4。如果您使用的是较低版本,请更新PHP或使用:

$group = $xml->xpath("/Event[@Group = 'MTCH']");
$group = $group[0];

答案 1 :(得分:0)

Michi的答案更正确,编码更好但我也发现在我的代码中加入节点'Market'也是如此:

$teamaname = $xml->Competition->Round[0]->Event[$i]->Market->EventSelections[0][EventSelectionName];
$teambname = $xml->Competition->Round[0]->Event[$i]->Market->EventSelections[1][EventSelectionName];