简单的 PHP XML 解析器


Simple PHP XML Parser

我是PHP的新手,所以如果可能的话需要一些帮助,这可能是一个非常简单的答案,但我正在努力。

我正在尝试从 William Hill XML 提要中获取一些数据。

我想拉出:

  • 竞争
  • 球队比赛
  • 开球时间
  • 球队 1 + 赔率
  • 平局+赔率
  • 球队 2 + 赔率

下面是指向 XML 源的链接 - http://cachepricefeeds.williamhill.com/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=1&marketSort=MR&filterBIR=N

到目前为止,我有下面的代码,它没有提取我需要的所有数据,它只带回了一个灯具。

<?php 
$xml = simplexml_load_file('http://cachepricefeeds.williamhill.com/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=1&marketSort=MR&filterBIR=N');

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

任何帮助将不胜感激!

已更新

    <?php
$xml = simplexml_load_file('http://cachepricefeeds.williamhill.com/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=1&marketSort=MR&filterBIR=N');

$data = $xml->response->williamhill->class->type;
foreach($data as $type) {
    foreach($type->market as $market) {
        if(strpos($market['name'], "Match Betting")) {
            echo $market['name'] . "<br/>";
            $competition = $type['name'];
            $kickoff = $market['time'];
            $date = $market['date'];
            $ps = $market->participant;
            echo "Competition: " . $competition . "<br/>";
            echo "Kickoff: " . $kickoff . "<br/>";
            echo "Date: " . $date . "<br/>";
    foreach($ps as $p) {
        echo $p['name']." - ".$p['odds']."<br />";
    }
    echo "<br><br/>";
        }
    }
}
?>

只获得一个入场的原因是因为你没有循环浏览每个市场,它只会选择第一个市场并循环浏览第一组。您将需要添加一个额外的循环才能将每个条目打印到屏幕上,因为列出了多个type

Simplexml 对象不是数组,一开始可能会令人困惑。将对象转换为数组,处理起来要容易得多:

var_dump((array) $xml->response->williamhill->class->type->market));

这可以在结构中的任何点完成。请注意,属性存储在 @attributes 键下。