【问题标题】:Using xml attribute id in page url and on page在页面 url 和页面上使用 xml 属性 id
【发布时间】:2013-02-01 16:36:50
【问题描述】:

我正在通过 xml 提要提取有关体育赛事的数据,我正在使用 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);
    }
?>

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

我遇到的问题是在我的页面 event.php 上,我不断收到显示的 xml 提要中的第一个事件。要做到这一点,我正在使用:

<?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。但我不太确定如何做到这一点,知道如何解决这个问题吗?

【问题讨论】:

    标签: php xml arrays simplexml


    【解决方案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
        }
      } 
    

    【讨论】:

    • 感谢您,真正奇怪的是,如果我更改 IF 语句以运行市场属性,而不是参与者属性(并根据更改脚本的其余部分),它可以工作但正在运行它在参与者属性上除了我的页眉和页脚之外的任何内容都不会在屏幕上回显,它们是 php 包含的。知道为什么会这样吗?
    • 我的错误 - 请参阅我的编辑。您需要一个嵌套的 foreach(2 个循环)。外层循环遍历市场以找到与id 匹配的市场,然后内层循环遍历市场中的每个参与者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 2019-02-28
    • 2017-04-01
    • 2017-04-30
    • 1970-01-01
    • 2016-10-22
    相关资源
    最近更新 更多