在页面url和页面上使用xml属性id

时间:2013-02-01 16:36:51

标签: php xml arrays simplexml

我通过xml feed提取有关体育赛事的数据,我使用simplexml来完成这项工作。到目前为止,我已经有一个循环遍历所有事件的foreach循环,并将它们作为包含在<a>标记中的事件名称列表回显,指向页面 event.php?= id (id是通过名为id的events属性确定的。

使用

执行此操作
<?php
    $xml = simplexml_load_file("openbet_cdn.xml");
    foreach($xml->response->williamhill->class->type->market as $market) {
        $market_attributes = $market->attributes();
        printf("<a href=\"event.php?id=%s\">%s</a>\n", 
                    $market_attributes->id, 
                    $market_attributes->name);
    }
?>

我正在使用的Feed是http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N

我遇到问题的是我的网页event.php我继续显示xml Feed中的第一个事件。要使用以下方式执行此操作:

<?php 
  foreach ($xml->response->williamhill->class->type->market->participant as $participant) {   
  $participant_attributes = $participant->attributes();  

    echo "<tr>";
      // EVENT NAME
      echo "<td>";
        echo "<a href=".$market_attributes['url'].">";
        echo $participant_attributes['name'];//participants name
        echo "</a>";
      echo"</td>";

      //ODDS
      echo "<td>";
        echo $participant_attributes['odds'];
      echo "</td>"; 
    echo "</tr>";
  } 
?>

我可以理解为什么它是因为我没有引用事件页面的URL中的id。但是我不太清楚如何做到这一点,任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您只需在循环中添加if,以便仅定位与查询字符串中的事件ID匹配的事件ID。还需要一个嵌套循环,因为您希望遍历每个市场以找到匹配的id,然后遍历每个参与者。

  foreach ($xml->response->williamhill->class->type->market as $market) {   

    if($market->attributes()->id == $_GET['id']) {

        foreach($market->participant as $participant) {
            $participant_attributes = $participant->attributes();  

            echo "<tr>";
              // EVENT NAME
              echo "<td>";
                echo "<a href=".$market->attributes()->url.">";
                echo $participant_attributes['name'];//participants name
                echo "</a>";
              echo"</td>";

              //ODDS
              echo "<td>";
                echo $participant_attributes['odds'];
              echo "</td>"; 
            echo "</tr>";
        }

        break; // <-- we've found the target and echo'ed it so no need to keep looping
    }
  }