1

i'm trying to get some random website content for practicing purposes on my localhost. while i'm trying to code this ,i'm getting these two error.

  1. "Warning: file_get_contents(https://www.weather-forecast.com/locations/canada/forecasts/latest): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:\xampp\htdocs\weather\weather.php on line 8".

  2. " Undefined offset: 1 in C:\xampp\htdocs\weather\weather.php on line 12" Can anyone let me know what's the issue ? i guess it has something to do with spaces and i checked there isn't any i guess.

here's my code.

if($_GET['city'])
{
    $_GET['city'] = str_replace(' ',"",$_GET['city']);
    $forecastPage = file_get_contents("https://www.weather-forecast.com/locations/".$_GET['city']."/forecasts/latest");
    $pageArray = explode('<span class="b-forecast__table-description-title"><h2>London Weather Today</h2>(1&ndash;3 days)</span><p class="b-forecast__table-description-content"><span class="phrase">', $forecastPage);
    $secondpagearray = explode('</span></p></td>', $pageArray[1]);
    $weather = $secondpagearray[0];
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    The error is very clear, the URL you're trying to open doesn't exist. – Barmar Sep 20 '19 at 15:53
  • Try clicking on the link, you'll get an error from the browser. – Barmar Sep 20 '19 at 15:53
  • 1
    You should check for errors. The 2nd error is because you didn't get anything from the web site, so anything that tries to use the response will not work. – Barmar Sep 20 '19 at 15:54
  • try London instead of Canada, it works. the website doesn't show results for countries I guess? – cagri Sep 20 '19 at 15:55
  • also, you probably want to do `if(isset($_GET['city']))` or `if(!empty($_GET['city']))` – cagri Sep 20 '19 at 15:56

1 Answers1

0

The problem is quite simple, you have incorrect URL. As I can see site you provided accepts city names, not countries (e.g. https://www.weather-forecast.com/locations/Toronto/forecasts/latest).

Please take a look at this answer https://stackoverflow.com/a/4358138/8035872 about remote page error handling.

Also I would recommend you to use some of sites which provides static API, if you just need some weather forecast parsing whole HTML page isn't good way.

Zekfad
  • 189
  • 12