在外部xml feed中解析到php

时间:2013-01-21 16:19:53

标签: php xml xml-parsing simplexml

我真的很新,我试图将数据从外部xml feed加载到php文档中,然后使用该数据生成输出。

使用的xml Feed是 - http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=1&marketSort=--&filterBIR=N

我想要做的是生成一个“市场”列表和名称,因此在编写列表时前三个项目时xml提要是:

  • 苏格兰第1分部 - 冠军 - 冠军
  • Dumbarton v Hamilton - 上半场结果/下半场结果
  • Dumbarton v Hamilton - Match Handicaps

目前我试图使用下面的代码来实现这一点,但是我很快就无法使用它,关于我在这里做错了什么想法?

只是另一个背景,即时通讯使用php 5.4.4,我认为simplexml已预先安装好了..所以我不需要在这里添加任何其他东西吗?

<?php 

$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=1&marketSort=--&filterBIR=N');

foreach ($xml->market as $event) {
  echo $event;
}

?>

2 个答案:

答案 0 :(得分:3)

您需要深入了解xml以获取市场,然后获得市场的attributes

<?php 

$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=1&marketSort=--&filterBIR=N');

foreach ($xml->response->williamhill->class->type as $type) {
  $type_attrib = $type->attributes();
  echo "<p><h2>Type ".$type_attrib['id'].": ".$type_attrib['name']."</h2>";
  foreach ($type->market as $event) {
    $event_attributes = $event->attributes();
    echo $event_attributes['name']."<br />";
    //commented out the following which prints all attributes
    //replaced by above to just print the name
    /*
    echo "<p>";
    foreach($event->attributes() as $attrib=>$value) {
      echo "$attrib: $value <br />";
    }
    echo "</p>";
    */
  }
  echo "</p>";
}

答案 1 :(得分:0)

例如,您可以显示参与者的姓名和相应的赔率:

<?php 

$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=1&marketSort=--&filterBIR=N');


$data = $xml->response->williamhill->class->type->market;
$ps = $data->participant;
foreach($ps as $p)
{
    echo $p['name']." - ".$p['odds']."<br />";
}

?>