Scraper php returns a blank page

I am new to php and I created a scraper.php page where you can get weather information from http://www.weather-forecast.com "for any city.
I followed the instructor and I don’t understand why my code returns a blank page when it should return only a short three-day forecast

anyway ... 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]; ?> 
+5
source share
2 answers

This is not empty, but an error in your script. This is probably empty because you disable the error report.

From this line:

 preg_match('/3 Day Weather Forest Summary:<\/b><span class="phrase">(.*?)</span>',$contents, $matches); 

You forgot to go / to </span> (it should be <\/span> ); and there is no final delimiter / for preg_match. (There is a typo, it should be "Forecast" not Forest.)

But even you correct this error, you will not get what you are looking for, looking at the html source code from the weather forecast, you will miss <span class="read-more-small"><span class="read-more-content"> after <\/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 can use preg_match_all to get all three weather forecast forecasts (1-3 days, 4-7 days and 7-10 days), replacing your entire preg_match line with:

 preg_match_all('/<span class="phrase">(.*?)<\/span>/',$contents, $matches); 

and repeat your details:

$matches[0][0] in 1-3 days,
$matches[0][1] in 4-7 days,
$matches[0][2] for 7-10 days.

0
source

Try to complete this question:

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

to get what you are looking for.

Explanation:

file_get_contents() will provide you with the contents of a static page.

The content that you actually see in your browser is generated by HTML / CSS / JS, and will not be visible using the file_get_contents() function.

When I tried to go directly from my browser to this URL

(for example: new york )

and open page as a source, find: "3-day forest overview of the forest."

I had no results, so I assume this was your problem.

-1
source

Source: https://habr.com/ru/post/1239158/


All Articles