将外部XML源解析到PHP中

3
我对php非常陌生,我正在尝试从外部xml源加载数据到php文档中,然后使用这些数据生成输出。
我使用的xml源是- http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=1&marketSort=--&filterBIR=N 我的目标是生成一个“市场”和它们名称的列表,所以在撰写本文时,xml源中的前3个项目将是:
Scottish Division 1 - Outright - Outright Dumbarton v Hamilton - 1st Half Result/2nd Half Result Dumbarton v Hamilton - Match Handicaps
目前我正在尝试使用下面的代码来实现这一点,但我很快就走进了死胡同,请问我做错了什么? < p > 仅提供更多背景信息,我正在使用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;
}

?>

什么问题?它在这里工作正常。尝试打印_r($xml); - Ivo Pereira
@IvoPereira 我正在使用print_r($xml)成功获取整个feed,但是我在使用foreach循环时遇到了麻烦,无法提取<market id="39970574" name="Scottish Division 1 - Outright - Outright">这一部分。 - sam
嗨@sam,我需要这个旧API的WSDL(因为v2受ApiKey保护,我无法获取)。你有WSDL吗?非常感谢。 - Gabe
2个回答

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
顺便说一下,在测试时,您应该将XML文件保存到本地文件中,然后从那里加载它,这样会更快,也可以节省带宽。 - bencoder
感谢bencoder,这个可以用来格式化XML数据的输出,但它会输出每一个给定的属性,而不仅仅是名称。 - sam
嗨@sam,我已经更改了代码,现在它只会打印名称部分。我注释掉了打印所有属性的部分,这样你可以进行比较以帮助你理解。 - bencoder
非常感谢您的帮助,能够分解并了解每个部分的作用真的很有帮助。再次感谢。 - sam

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 />";
}

?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接