0

I'm trying to get the wheather data from http://www.weather-forecast.com/locations/Berlin/forecasts/latest

but preg_match just returns nothing

<?php

$contents=file_get_contents("http://www.weather-forecast.com/locations/Berlin/forecasts/latest");

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




print_r($matches)


?>
JangoCG
  • 823
  • 10
  • 23
  • 1
    To start it is `3 Day Weather Forecast Summary:` not `3Day Weather Forecast Summary:`. You should look into using a parser though, and/or a weather API. Here's one I've used, http://apidev.accuweather.com/developers/. – chris85 May 26 '16 at 12:07
  • Try DOMDocument instead. Parsing HTML with regular expressions is very difficult to get right and resulting code is hard to maintain. – Álvaro González May 26 '16 at 12:08
  • @choz You can read url using `file_get_contents` – Justinas May 26 '16 at 12:10
  • @chris85 My bad.. It turns out to be working just fine.. – choz May 26 '16 at 12:11
  • Obligatory link to [Please don't use regex for markup languages](http://stackoverflow.com/a/1732454/2370483) – Machavity May 26 '16 at 12:23

1 Answers1

2

Don't use a regex to parse html, user an html parser like DOMDocument,

$contents = file_get_contents("http://www.weather-forecast.com/locations/Berlin/forecasts/latest");
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($contents);
$x = new DOMXpath($dom);
foreach($x->query('//span[contains(@class,"phrase")]') as $phase)
{
    echo $phase->textContent; 
}
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268