使用PHP和SimpleXML显示XML子数据

时间:2016-10-10 21:59:56

标签: php xml

我是PHP和XML的新手。我试图从我认为是XML文件的子元素中提取特定元素。

主要课程为<events><event>课程中有多个<events>。我试图从XML文件中提取特定数据并显示它们。

<?php
$xml = simplexml_load_file('http://xml.pinnaclesports.com/pinnaclefeed.aspx?sporttype=Football&sportsubtype=nfl');
foreach($xml->children() as $event){
    echo $event->participants->participant->participant_name . ", ";
    echo $event->participants->participant[1]->participant_name . ", ";
    echo $event->periods->period->spread->spread_visiting . ", ";
    echo $event->periods->period->total->over_adjust . "<br>";
}
?>

这是输出,没有PHP error_log条目:

, , ,
, , ,
, , ,
, , , 

我感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

要访问嵌套元素,您只需遵循从上下文元素(event)开始到目标元素的元素路径。如果正确格式化XML,将更容易看到路径/层次结构:

foreach($xml->children() as $event) {
    echo $event->participants->participant->participant_name . ", ";
    echo $event->participants->participant[1]->participant_name . ", ";
    echo $event->periods->period->spread->spread_visiting . ", ";
    echo $event->periods->period->total->over_adjust . "<br>";
}

<强> eval.in demo

输出

Denver Broncos, San Diego Chargers, -3, 101<br>