我正在尝试构建一个天气刮板应用程序。出于某种原因,这个PHP代码给了我错误
$city = $_GET['city'];
$city = str_replace(" ","",$city);
$contents = file_get_contents("http://www.weather-forecast.com/locations/".$city."/forecasts/latest");
preg_match('/3 Day Weather Forecast Summary:<\/b><span class="read-more-small"><span class="read-more-content"> <span class="phrase">(.*?)</s',$contents,$matches); //use single quotes ' " " ' if double quotes are inside
echo($matches[0]);
如果我没有输入city = new york,那么会给我以下错误,如果我拼写错误的城市名称,它会给我同样的错误,因为$city
是空的,有错误的值...是有没有办法解决它?
答案 0 :(得分:0)
$city=!empty( $_GET['city'] ) ? $_GET['city'] : false;
if( $city ){
$city=str_replace( " ", "", $city );
$contents=@file_get_contents( "http://www.weather-forecast.com/locations/".$city."/forecasts/latest" );
if( $contents ){
preg_match('/3 Day Weather Forecast Summary:<\/b><span class="read-more-small"><span class="read-more-content"> <span class="phrase">(.*?)</s',$contents,$matches); //use single quotes ' " " ' if double quotes are inside
echo($matches[0]);
} else {
echo "Bad foo!";
}
} else {
echo "No city";
}
正如@jan所示,我也认为DOMDocument
&amp; DOMXPath
为preg_match
...
$city=!empty( $_GET['city'] ) ? $_GET['city'] : false;
if( $city ){
$city=str_replace( " ", "", $city );
$url="http://www.weather-forecast.com/locations/{$city}/forecasts/latest";
$contents=@file_get_contents( $url );
if( $contents ){
$dom=new DOMDocument;
$dom->loadHTML($contents);
$xp=new DOMXPath($dom);
$col=$xp->query('//div[@class="forecast-content"]/p[@class="summary"]/span/span/span');
foreach($col as $node){
$header=$node->parentNode->parentNode->parentNode->firstChild->nodeValue;
$description=$node->nodeValue;
echo '<h4>' . $header . '</h4><div>' . $description . '</div>';
}
} else {
echo "Bad foo!";
}
} else {
echo "No city";
}
答案 1 :(得分:0)
问题是:为什么? ...而不是使用DOM parser
例如。对于古老的德国可爱的首都:
<?php
$url = 'http://www.weather-forecast.com/locations/Berlin/forecasts/latest';
$html = file_get_contents($url);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
$text = $xpath->query("//p[@class='summary'][1]//span[@class = 'phrase']");
echo $text->item(0)->textContent;
?>
脚本返回Mostly dry. Warm (max 25°C on Wed afternoon, min 11°C on Mon night). Wind will be generally light.
要获得所有预测,请省略[1]
并循环结果。