Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scraper php returning a blank page

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];
?>
like image 534
user3084840 Avatar asked Nov 26 '22 05:11

user3084840


1 Answers

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];
?>


Or

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.

like image 62
cwps Avatar answered Nov 28 '22 19:11

cwps