I am new to php and I have made a scraper.php page where you can retrieve weather information from "http://www.weather-forecast.com" for any given city.
I was following the instructor and I cannot see why my code is returning a blank page when its supposed to return just a brief 3 day forcast
anyways...here is my code
<?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];
?>
It's not blank, but error in your script. It's blank probably because you turn off the error reporting.
From this line:
preg_match('/3 Day Weather Forest Summary:<\/b><span class="phrase">(.*?)</span>',$contents, $matches);
You forgot to escape /
on the </span>
(it should be <\/span>
); and there's no ending delimiter /
for the preg_match. (There is a typo there, it should be 'Forecast' not Forest.)
But even you fix those error, you wouldn't get what your looking for because looking at the html source code from the weather-forecast, you skip the <span class="read-more-small"><span class="read-more-content">
after the <\/b>
.
So, it should be like this:
<?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];
?>
You could use preg_match_all
to get all three Weather Forecast Summary (1 – 3 Day, 4 – 7 Day, and 7 – 10 Day), by replacing all your preg_match
line with :
preg_match_all('/<span class="phrase">(.*?)<\/span>/',$contents, $matches);
and echo your data:
$matches[0][0]
for the 1-3 day,$matches[0][1]
for the 4-7 day,$matches[0][2]
for the 7-10 day.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With