banniere
Ecrit par leknoppix le 7-01-2010 à 18:16:09
La météo sur votre site internet

Bonjour à tous et bonne année. A peine rentré dans 2010 que nous avons déjà des belles surprises, la neige pour certains et le froid pour d'autres. Sur leknoppix's blog, sa sera encore une année avec des découvertes musicale mais également des nouveaux dans les tutos ainsi que dans les scripts qui seront mis en ligne. Récemment, j'ai découvert sur internet, une classe php qui permettait de récupérer le temps qu'il fait sur une ville précise.

Cette classe est très simple en utilisation et rapide à mettre en place. Ci dessous la classe php necessaire, elle utilise une méthode curl():

 

<?php
 
if(isset($_GET['source'])) {
    highlight_file(__FILE__);
    die;
}
 
/***************************************************************
*
* 09/05/2009
*
* Copyright notice
*
* (c) 2009 Yohann CERDAN <cerdanyohann@yahoo.fr>
* All rights reserved
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
  class GoogleWeatherAPI { /** City code input **/ private $city_code = '';   /** City label get on the google webservice **/ private $city = '';   /** Domain of the google website **/ private $domain = 'www.google.com';   /** Prefix of the img link **/ private $prefix_images = '';   /** Array with current weather **/ private $current_conditions = array();   /** Array with forecast weather **/ private $forecast_conditions = array();   /** If the city was found **/ private $is_found = true;   /** The HTML response send by the service **/ private $response;   /**
* Class constructor
* @param $city_code is the label of the city
* @param $lang the lang of the return weather labels
* @return ...
*/
  function __construct ($city_code,$lang='fr') { $this->city_code = $city_code; $this->prefix_images = 'http://'.$this->domain; $this->url = 'http://'.$this->domain.'/ig/api?weather='.urlencode($this->city_code).'&hl='.$lang;   $getContentCode = $this->getContent($this->url);   if($getContentCode == 200) {   $content = utf8_encode($this->response);   $xml = simplexml_load_string($content);   if(!isset($xml->weather->problem_cause)) {   $xml = simplexml_load_string($content);   $this->city = (string)$xml->weather->forecast_information->city->attributes()->data;   $this->current_conditions['condition'] = (string)$xml->weather->current_conditions->condition->attributes()->data; $this->current_conditions['temp_f'] = (string)$xml->weather->current_conditions->temp_f->attributes()->data; $this->current_conditions['temp_c'] = (string)$xml->weather->current_conditions->temp_c->attributes()->data; $this->current_conditions['humidity'] = (string)$xml->weather->current_conditions->humidity->attributes()->data; $this->current_conditions['icon'] = $this->prefix_images.(string)$xml->weather->current_conditions->icon->attributes()->data; $this->current_conditions['wind_condition'] = (string)$xml->weather->current_conditions->wind_condition->attributes()->data;   foreach($xml->weather->forecast_conditions as $this->forecast_conditions_value) { $this->forecast_conditions_temp = array(); $this->forecast_conditions_temp['day_of_week'] = (string)$this->forecast_conditions_value->day_of_week->attributes()->data; $this->forecast_conditions_temp['low'] = (string)$this->forecast_conditions_value->low->attributes()->data; $this->forecast_conditions_temp['high'] = (string)$this->forecast_conditions_value->high->attributes()->data; $this->forecast_conditions_temp['icon'] = $this->prefix_images.(string)$this->forecast_conditions_value->icon->attributes()->data; $this->forecast_conditions_temp['condition'] = (string)$this->forecast_conditions_value->condition->attributes()->data; $this->forecast_conditions []= $this->forecast_conditions_temp; } } else { $this->is_found = false; }   } else { trigger_error('Google results parse problem : http error '.$getContentCode,E_USER_WARNING); return null; } }   /**
* Get URL content using cURL.
*
* @param string $url the url
*
* @return string the html code
*/
  public function getContent($url) { if (!extension_loaded('curl')) { throw new Exception('curl extension is not available'); }   $curl = curl_init(); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_URL, $url); $this->response = curl_exec($curl); $infos = curl_getinfo($curl); curl_close ($curl); return $infos['http_code']; }   /**
* Get the city
*/
  function getCity() { return $this->city; }   /**
* Get the current weather
*/
  function getCurrent() { return $this->current_conditions; }   /**
* Get the forecast weather
*/
  function getForecast() { return $this->forecast_conditions; }   /**
* If teh city was found
*/
  function isFound() { return $this->is_found; }   } ?>

La création d'un fichier contenant cette classe ne sera pas difficile. Ensuite, sur la page sur laquelle vous voulez inclure la météo, et un appel de classe et le tour est joué, vous avez la méthode. Voici comment récupérer la météo d'une ville:

<?php
$gweather = new GoogleWeatherAPI('toulouse','fr'); // "en" also work
if($gweather->isFound()) {
	echo '<pre>'; print_r($gweather->getCity()); echo '</pre>';
	echo '<pre>'; print_r($gweather->getCurrent()); echo '</pre>';
	echo '<pre>'; print_r($gweather->getForecast()); echo '</pre>';
}
?>
Lors de la création de l'instance, nous devons indiquer la ville, dans l'exemple, il s'agit de toulouse. Ensuite la fonction isFound() vérifie sur la ville est présente dans les villes possédant la météo. Les instructions suivants permette de regarder la ville, le temps ainsi que les prévisions. Je ne vais pas présenter l'ensemble de la classe car elle est commenté. Avec le code précédent, il est vrai qu'il n'y a pas de présentation, à vous de présenter comme bon vous semble. Je vous met ci-dessus une présentation assez simple permettant d'afficher le temps pour la journée en cours.

<!-- City -->
 
	<div>
		<h2>Météo à <?php if($gweather->isFound()) { echo $city; } ?></h2>
	</div>
 
	<!-- Current temp -->
 
	<div class="current">
		<?php if($gweather->isFound()) { echo '<div class="icon" ><img src="'.$currentTemp['icon'].'"/></div>'; } ?>
 
			<p>
				<strong><?php if($gweather->isFound()) { echo $currentTemp['temp_c']; } ?> °C</strong><br />
				Actuellement : <?php if($gweather->isFound()) { echo $currentTemp['condition']; } ?><br />
				Vent : <?php if($gweather->isFound()) { echo $currentTemp['wind_condition']; } ?><br />
				Humidité : <?php if($gweather->isFound()) { echo $currentTemp['humidity']; } ?><br />
			</p>
 
	</div>
J'espère que cette classe vous servira autant que pour moi. Bonne journée et à bientôt.

 

 

Publier sur mon compte twitterPublier sur mon viadeoPublier sur mon deliciousPublier sur mon compte twitter

Ajoute ton commentaire

Pseudo : *
E-Mail : *
MSN :
Site internet :
Blog :
Note : *
Commentaire : *
Ne pas compléter :

Le 11-01-2010 à 17:16:34 par misslilou

avatarMoi je vois bien ça sur certains sites futur. Excellent script.

Note :  notenotenotenotenote
Le 7-01-2010 à 21:07:16 par Regis38

avatarJe trouve sa pas mal, dommage que je n'est plus mon site sinon je l'aurai testé.

Note :  notenotenotenotenote
© 2007-2024