通过PHP错误解析XML数据

时间:2013-08-29 14:55:37

标签: xml soap php

我正在尝试从API中打印出这个xml。

<XMLSOCCER.COM>
<Match>
<Id>309389</Id>
<Date>2013-08-04T16:00:00+02:00</Date>
<League>Scottish Premier League</League>
<Round>1</Round>
<HomeTeam>St Johnstone</HomeTeam>
<HomeTeam_Id>46</HomeTeam_Id>
<HomeGoals>1</HomeGoals>
<AwayTeam>Hearts</AwayTeam>
<AwayTeam_Id>50</AwayTeam_Id>
<AwayGoals>0</AwayGoals>
<Time>Finished</Time>
<Location>McDiarmid Park</Location>
<HomeTeamYellowCardDetails>83': Murray Davidson;</HomeTeamYellowCardDetails>
<AwayTeamYellowCardDetails>78': Jamie Hamill;</AwayTeamYellowCardDetails>
<HomeTeamRedCardDetails/>
<AwayTeamRedCardDetails/>
</Match>
<Match>
<Id>309390</Id>
<Date>2013-08-03T16:00:00+02:00</Date>
<League>Scottish Premier League</League>
<Round>1</Round>
<HomeTeam>Aberdeen</HomeTeam>
<HomeTeam_Id>45</HomeTeam_Id>
<HomeGoals>2</HomeGoals>
<AwayTeam>Kilmarnock</AwayTeam>
<AwayTeam_Id>52</AwayTeam_Id>
<AwayGoals>1</AwayGoals>
<Time>Finished</Time>
<Location>Pittodrie Stadium</Location>
<HomeTeamYellowCardDetails>39': Jonathan Hayes;</HomeTeamYellowCardDetails>
<AwayTeamYellowCardDetails>38': James Fowler;18': Christopher Johnston;</AwayTeamYellowCardDetails>
<HomeTeamRedCardDetails/>
<AwayTeamRedCardDetails/>
</Match>
</XMLSOCCER.COM>

这是我到目前为止编写的PHP代码:

foreach($response->Match as $match){
        print "{$match->HomeTeam}<br />\n";
        }

    print $response -> {"XMLSOCCER.COM"};

但我似乎无法获得任何输出,我不断收到错误,例如:

  • 未定义的属性:stdClass ::
  • 尝试获取
  • 中的非对象属性

我只是想知道是否有人能指出我正确的方向。目前我只想打印一个HomeTeam名称,从这里我可以进一步发展。

2 个答案:

答案 0 :(得分:0)

我认为他的$ response变量只是来自API调用的RAW响应。如果这是正确的,您需要将该$响应加载到PHP simplexml_load_string 函数中,或者使用 simplexml_load_file 加载API调用,然后才能像对象一样使用变量。这些函数将为您提供一个SimpleXMLElement对象,以便您可以执行$ xml-&gt; Match

之类的操作。

simplexml_load_string:http://php.net/manual/en/function.simplexml-load-string.php

答案 1 :(得分:0)

您可以按如下方式解析xml Feed,您可以使用simplexml_load_file

$feed_url="your xml feed url";

    $response = simplexml_load_file($feed_url);

    print_r($response);

   foreach($response->Match as $match)
   {
    echo "{$match->HomeTeam}<br />\n";
    }