5

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];
?>
user3084840
  • 111
  • 1
  • 6

2 Answers2

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


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.

cwps
  • 367
  • 1
  • 6
-1

Try following this question:

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

to get what you're looking for.

Explanation:

file_get_contents() will give you the static page content.

The contents you actually see in your browser is generated by the HTML/CSS/JS, and won't be seen with the file_get_contents() function.

When I tried to browse directly from my browser, to that url

(for example: new york)

and opened page as source, search for: "3 Day Weather Forest Summary:".

I didn't got any results, so I'm assuming that was your problem.

Community
  • 1
  • 1
Captain Crunch
  • 567
  • 3
  • 13