Magazine High tech

Une classe PHP pour récupérer la météo

Publié le 26 avril 2009 par Ekevin

Voici une classe compatible PHP 5 pour récupérer la météo. Pour l’instancier il faut passer en paramètre le code de votre ville (à récupérer sur le site de Yahoo!Weather - exemple pour Oxford : UKXX0106) ainsi que l’unité pour la température (c ou f - optionnel c pour Celcius par défaut).

Exemple d’utilisation avec le shell interactif :

$ php -a
Interactive shell

php > include 'class.weather.php';
php > $meteo = new YWeather('UKXX0106', 'c');
php > print_r($meteo);
YWeather Object
(
    [_locationCode:protected] => UKXX0106
    [_urlComplete:protected] => http://weather.yahooapis.com/forecastrss?p=UKXX0106&u=c
    [_unit:protected] => c
    [weather] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [version] => 2.0
                )

            [channel] => SimpleXMLElement Object
                (
                    [title] => Yahoo! Weather - Oxford, UK
                    [link] => http://us.rd.yahoo.com/dailynews/rss/weather/Oxford__UK/*http://weather.yahoo.com/forecast/UKXX0106_c.html
                    [description] => Yahoo! Weather for Oxford, UK
...
php > $channel = $meteo->channel();
php > $item = $meteo->item();
php > print_r($item);
stdClass Object
(
    [condition] => stdClass Object
        (
            [text] => SimpleXMLElement Object
                (
                    [0] => Fair
                )

            [code] => SimpleXMLElement Object
                (
                    [0] => 34
...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
<?php
 
/**
 * Copyright (c) 2009, Kevin Etienne, http://www.pasunclou.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author Kevin Etienne <[email protected]>
 * @version 0.1
 * @package YWeather
 */
 
/**
 * This class get the Weather from Yahoo!Weather and
 * parses it into a weather object with usable attributes.
 */
class YWeather {
 
  /**
   * Store the location's code of the city
   * @private
   */
  protected $_locationCode;
  /**
   * Store the url of the API
   * @private;
   */
  protected $_urlComplete;
  /**
   * Store the unit's preference of the user and force him to retrieve the unit
   * throught the API (if the unit is not valid)
   * @private
   */
  protected $_unit;
 
  /**
   * create an instance of simpleXML
   * 
   * @param string $location code belong to the location (ex: UKXX0106)
   * @param char $unit unit for temperature (c or f) 
   */  
  public function __construct($location, $unit = 'c')
  {
    $this->_locationCode = $location;
    $this->_unit = $unit;
 
    $this->_urlComplete = $this->_buildURI($this->_locationCode, $this->_unit);
    $this->weather = simplexml_load_file($this->_urlComplete);
  }
 
  /**
   * call a protected method
   *
   * @param string $methodName name of the method
   * @param string $args N/A
   * @return an object for the Yahoo!Weather's namespace
   */
  public function __call($methodName, $args)
  {
    $method = "_get"  ucfirst( strtolower($methodName) );
    if (method_exists($this, $method))
    {
      return $this->$method();
    }
  }
 
  /**
   * return the complete URL to retrieve the Yahoo API
   * 
   * @param string $location code belongs to the location
   * @param char $unit unit in (c)elcius or (f)ahraneit
   * @return url composed with $location and $unit
   */
  protected function _buildURI($location, $unit = 'c')
  {
    $urlComplete = 'http://weather.yahooapis.com/forecastrss?';
    $urlComplete .= 'p='  $location;
    $urlComplete .= $unit ? '&u='  $unit : '';
    return $urlComplete;
  }
 
  /**
   * Largely inspired by the snippet originately written by
   * {@link http://pkarl.com Pete Karl} (2009).
   *
   * return an object with the location, units, wind, atmosphere and
   * astronomy parameters
   * 
   * @return object from the API namespace
   */
  protected function _getChannel()
  {
    $yWeather = $this->weather->channel->children("http://xml.weather.yahoo.com/ns/rss/1.0");
    foreach ($yWeather as $x => $channel_item)
      foreach ($channel_item->attributes() as $k => $attr)
        $yw_channel->$x->$k = $attr;
    return $yw_channel;
  }
 
  /**
   * Largely inspired by the snippet originately written by
   * {@link http://pkarl.com Pete Karl} (2009).
   * 
   * return an object with the geolocalisation, condition and forecast
   * 
   * return object from the API namespace
   */
  protected function _getItem()
  {
    $yWeather = $this->weather->channel->item->children("http://xml.weather.yahoo.com/ns/rss/1.0");
    foreach ($yWeather as $x => $yw_item)
    {
      foreach ($yw_item->attributes() as $k => $attr)
      {
        if($k == 'day') $day = $attr;
        if($x == 'forecast')
        {
          $yw_forecast->$x->$day->$k = $attr;
        }
        else $yw_forecast->$x->$k = $attr;
      }
    }
    return $yw_forecast;
  }
 
  /**
   * return the URL
   */
  public function __toString() {
    return $this->_urlComplete;
  }
 
}

Télécharger la classe YWeather.php


Retour à La Une de Logo Paperblog

A propos de l’auteur


Ekevin 5 partages Voir son profil
Voir son blog

l'auteur n'a pas encore renseigné son compte l'auteur n'a pas encore renseigné son compte