为什么这个PHP没有正确解析XML?

时间:2009-10-26 05:52:17

标签: php html xml parsing yahoo-weather-api

我试图通过this脚本解析Yahoo的天气XML Feed。解析本身是有效的:我正在努力争取今天,明天和后天的日子。

最终的HTML输出如下所示:

可在此处看到:http://www.wdmadvertising.com.au/preview/cfs/index.shtml

todayMon______________19

todayTue______________26

Tue______________26

应该看起来像这样:

Today______________(temp)

(tomrrow)______________(temp)

(day after tomorrow)______________(temp)

PHP和HTML:

<div class="latest-weather">
    <h1 class="latest-weather">Latest weather</h1>

    include("class.xml.parser.php");
    include("class.weather.php");

$weather_adelaide = new weather("ASXX0001", 3600, "c", $cachedir);

    $weather_adelaide->parsecached(); 

    // TODAY 1

    for ($day=0; isset($weather_adelaide->forecast[$day]); $day++) {
    print "<h2>today".$weather_adelaide->forecast[$day]['DAY']."</h2>";     
    print "<p />".$weather_adelaide->forecast[$day]['HIGH']."<br>"; }

    // FORECAST 2

    for ($day=1; isset($weather_adelaide->forecast[$day]); $day++) {
    print "<h2>".$weather_adelaide->forecast[$day]['DAY']."</h2>";     
    print "<p />".$weather_adelaide->forecast[$day]['HIGH']."<br>"; }

    // FORECAST 3   

    for ($day=2; isset($weather_adelaide->forecast[$day]); $day++)  {
    print "<h2>".$weather_adelaide->forecast[$day]['DAY']."</h2>";          
    print "<p />".$weather_adelaide->forecast[$day]['HIGH']."<br>"; }

?>

</div><!--/latest-weather-->

2 个答案:

答案 0 :(得分:2)

要么你不清楚for循环如何工作,要么你只是犯了一个非常愚蠢的错误。

如果是前者,请记住

for($x=0; isset(blah); $x++) {
    ...
}

相当于

$x = 0;
while(isset(blah)) {
    ...
    $x++;
}

看起来你获取今天和明天的预测;你的第一个循环产生:

todayMon______________19

todayTue______________26

你的第二个循环产生:

Tue______________26

你的第三个循环什么也没产生。

您应该将代码更改为以下内容:

// TODAY 1

if (isset($weather_adelaide->forecast[0])) {
    print "<h2>today</h2>";
    print "<p />".$weather_adelaide->forecast[0]['HIGH']."<br>";
}

// More days

for ($day=1; $day < 3 && isset($weather_adelaide->forecast[$day]); $day++) {
    print "<h2>".$weather_adelaide->forecast[$day]['DAY']."</h2>";
    print "<p />".$weather_adelaide->forecast[$day]['HIGH']."<br>";
}

另一条评论:我看到你使用<p />但是你也使用<br>,这很令人费解。 <br>无效XHTML。

答案 1 :(得分:0)

我认为设置了$weather_adelaide->forecast[0]$weather_adelaide->forecast[1],因此您第一次打印for 2次,打印第二次if。我认为您需要for而不是// TODAY 1 $day = 0; if(isset($weather_adelaide->forecast[$day])) { print "<h2>today".$weather_adelaide->forecast[$day]['DAY']."</h2>"; print "<p />".$weather_adelaide->forecast[$day]['HIGH']."<br>"; } // FORECAST 2 ++$day; if (isset($weather_adelaide->forecast[$day])) { print "<h2>".$weather_adelaide->forecast[$day]['DAY']."</h2>"; print "<p />".$weather_adelaide->forecast[$day]['HIGH']."<br>"; } // FORECAST 3 ++$day; if (isset($weather_adelaide->forecast[$day])) { print "<h2>".$weather_adelaide->forecast[$day]['DAY']."</h2>"; print "<p />".$weather_adelaide->forecast[$day]['HIGH']."<br>"; } :(未经过测试)

foreach(range(0, 2) as $i)

但是我会使用if并使用{{1}}

处理特殊的今日案例