2015-12-24 143 views
5

我是新来的php,我做了一个scraper.php页面,你可以从任何给定的城市检索“http://www.weather-forecast.com”的天气信息。
我下面的教练,我不明白为什么我的代码返回一个空白页时,它应该只返回一个简短的3天FORCASTscraper php返回空白页

反正...这里是我的代码

<?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 Forest Summary:<\/b> 
<span class="phrase">(.*?)</span>',$contents, $matches); 
echo $matches[1]; 
?> 
+0

你试过调试过吗?什么是城市?你在$内容中得到什么? etc – pvg

+0

空白可能意味着语法错误http://php.net/manual/en/function.error-reporting.php –

回答

-1

尝试以下这个问题:

how-can-i-emulate-a-get-request-exactly-like-a-web-browser

,让你在找什么。

说明:

file_get_contents()会给你的静态页面内容。

您在浏览器中实际看到的内容由HTML/CSS/JS生成, ,并且不会在file_get_contents()函数中看到。

当我试图直接从我的浏览器浏览,该URL

(例如:new york

,打开网页源,搜索:“3天林摘要:”。

我没有得到任何结果,所以我假设这是你的问题。

0

这不是空白,但脚本错误。这可能是因为你关闭了错误报告。

从这一行:

preg_match('/3 Day Weather Forest Summary:<\/b><span class="phrase">(.*?)</span>',$contents, $matches); 

你忘了在</span>(应该是<\/span>)逃脱/; preg_match没有结尾分隔符/。 (这里有一个输入错误,它应该是'Forecast'not Forest。)

但即使你修复了这些错误,你也不会得到你想要的东西,因为从天气预报中查看html源代码,您在<\/b>之后跳过<span class="read-more-small"><span class="read-more-content">

所以,它应该是这样的:

<?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">(.*?)<\/span>/',$contents, $matches); 
echo $matches[1]; 
?> 


或者

你可以使用preg_match_all获得全部三个天气预报摘要(1 - 3天,4 - 7日,和7 - 10日),将您所有的preg_match行替换为:

preg_match_all('/<span class="phrase">(.*?)<\/span>/',$contents, $matches); 

和回声数据:

$matches[0][0]为1-3天,
$matches[0][1]为4-7天,
$matches[0][2]为7-10天。