1

I'm trying to pull the weather from the weather network. This code gives it to me, but it looks pretty long, and returns two values in the array (that's why I need to return $output[1] and not $output[0]), when I only want it to return one. Any ideas?

$url=file_get_contents("http://www.theweathernetwork.com/weather/cans0057?ref=homecity");

preg_match('/<div id="obs_conds" class="hslice">.*?<img.*?alt="(.*?)".*?<\/div>/s',$url,$output);

print_r($output[1]);
bozdoz
  • 12,550
  • 7
  • 67
  • 96
  • 3
    Don't regex HTML - Parse it. HTML is not Regular. – zellio Jul 16 '11 at 19:24
  • 1
    *(related)* [Best Methods to parse HTML](http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662) – Gordon Jul 16 '11 at 19:44
  • 1
    The Weather Channel also provides the weather data as RSS Feed which is much easier to parse: `echo simplexml_load_file('http://rss.theweathernetwork.com/weather/cans0057')->channel->item[0]->description;` – Gordon Jul 16 '11 at 19:57
  • 1
    Your code was my best option. Thanks Gordon! – bozdoz Jul 16 '11 at 20:45

2 Answers2

3

I think it's great. Maybe you can make shortcut from it

preg_match('/class="hslice">.*?<img.*?alt="(.*?)"/s',$url,$output);
genesis
  • 50,477
  • 20
  • 96
  • 125
0

I believe preg_matches returns the whole match in the the first element of the array $output[1] and $output[1] the text that matched the first captured parenthesized subpattern, and so on (http://php.net/manual/en/function.preg-match.php). Regarding the regex optimization, I guess you're trying to pull everything inside <div id="obs_conds" class="hslice">, if that is the case I would try to do a dom search instead.

On the other hand maybe the best solution is to contact the site and set a webservice client. It seems to me that they do have the infrastucture for that.

Erick Martinez
  • 805
  • 1
  • 9
  • 11