2015-12-24 140 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天。