Benutzer: Gast
Eintrag: Wetterdaten mit openweathermap.org-API

Wetterdaten mit openweathermap.org-API

von: marcel
Tags: PHP, Wetter, Script
Kreise: HTML / CSS / JS

Kleines Script, um die Wetterdaten von openweathermap.org zu holen und auf der Webseite anzeigen zu lassen. Das Script benutzt einen simplen kleinen File-Cache.

weather.php

Code: PHP
<?php
setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');

/**
 * Copyright of the weatherdata and api: http://openweathermap.org/copyright
 * Copyright of this script: none - do what you want.
 * This script is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 **/

class weather {
  
  /**
   * the cache-file
   * @var string
   */
  protected $file_name = "weather.data";
  
  /**
   * Lifetime of the cache
   * @var integer
   */
  protected $file_lifetime = 3600;
  
  /**
   * The city you are searching for 
   * @var string
   */
  protected $city;
  
  /**
   * @return void
   */
  public function __construct() {
    
  }
  
  /**
   * Call this method after setting the city.
   * @return string
   */
  public function main() {
    // check, if cache exists and is not outdated
    if (is_file($this->file_name) && filemtime($this->file_name) > time() - $this->file_lifetime) { // get the content from cache-file
      return self::_readfile($this->file_name);
    } else { // generate content and save in cache-file
      $content = self::_getWeatherHtml();
      if ($content) {
        self::_writefile($this->file_name, $content);
      } else {
        // if content could not be generated, try to get the outdated content from file
        if (is_file($this->file_name)) {
          $content = self::_readfile($this->file_name);
        }
      }
      
      // return by type
      switch ($_GET['type']) {
        default:
        case "html":
          return $content;
          break;
        case "json":
          return json_encode(array(
            "success" => true,
            "content" => $content
          ));
          break;
      }
    }
  }
   
  /**
   * Setter for the city
   * @param string $city
   */
  public function setCity($city) {
    $this->city = $city;
  }
  
  /**
   * Method to get the data from openweathermap.org.
   * @return string The HTML-Output
   */
  private function _getWeatherHtml() {
    $content = "";
    if (isset($this->city)) {
      $url = 'api.openweathermap.org/data/2.5/weather?q=' . urlencode($this->city);
      
      $curl = curl_init();
      $headers = array();
      curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($curl, CURLOPT_HEADER, 0);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_TIMEOUT, 30);
      $json = curl_exec($curl);
      curl_close($curl);

      $data = json_decode($json);
      #print_r( $data);
      
      if (!empty($data->cod) && $data->cod = "200") {
        
        $dataOut = Array();
        
        if ($data->main->temp) {
          $dataOut['Aktuell'] = number_format($data->main->temp - 273.15, 1, ',', '') . " °C";
        }
        
        if ($data->main->temp_min) {
          $dataOut['Heute min'] = number_format($data->main->temp_min - 273.15, 1, ',', '') . " °C";
        }
        
        if ($data->main->temp_max) {
          $dataOut['Heute max'] = number_format($data->main->temp_max - 273.15, 1, ',', '') . " °C";
        }
        
        if ($data->main->pressure) {
          $dataOut['Luftdruck'] = number_format($data->main->pressure, 0, ',', '') . " hPa";
        }
        
        if ($data->main->humidity) {
          $dataOut['Luftfeuchtigkeit'] = number_format($data->main->humidity, 0, ',', '') . " %";
        }
        
        if ($data->rain->{'1h'}) {
          $dataOut['Niederschlag'] = number_format($data->rain->{'1h'}, 1, ',', '') . " mm (letzte Stunde)";
        } else if ($data->rain->{'3h'}) {
          $dataOut['Niederschlag'] = number_format($data->rain->{'3h'}, 1, ',', '') . " mm (letzte 3 Stunden)";
        } else if ($data->rain->{'6h'}) {
          $dataOut['Niederschlag'] = number_format($data->rain->{'6h'}, 1, ',', '') . " mm (letzte 6 Stunden)";
        } else if ($data->rain->{'12h'}) {
          $dataOut['Niederschlag'] = number_format($data->rain->{'12h'}, 1, ',', '') . " mm (letzte 12 Stunden)";
        } else if ($data->rain->{'24h'}) {
          $dataOut['Niederschlag'] = number_format($data->rain->{'24h'}, 1, ',', '') . " mm (letzte 24 Stunden)";
        }
        
        if ($data->snow) {
          $dataOut['Schnee'] = number_format($data->snow, 1, ',', '') . " mm";
        }
        
        if ($data->sys->sunrise) {
          $dataOut['Sonnenaufgang'] = date("H:i", $data->sys->sunrise). " Uhr";
        }
        
        if ($data->sys->sunset) {
          $dataOut['Sonnenuntergang'] = date("H:i", $data->sys->sunset) . " Uhr";
        }
        
        if ($data->clouds->all) {
          $dataOut['Bew&ouml;lkung'] = number_format($data->clouds->all, 0, ',', '') . " %";
        }
        
        if ($data->wind->speed) {
          $dataOut['Wind'] = number_format($data->wind->speed, 1, ',', '') . " m/s";
        }
        
        if ($data->wind->gust) {
          $dataOut['Windb&ouml;en'] = number_format($data->wind->gust, 1, ',', '') . " m/s";
        }
        
        if ($data->wind->deg) {
          $dataOut['Windrichtung'] = $data->wind->deg . " °";
        }
        
        if ($data->dt) {
          $dataOut['Messung'] = strftime("%A, %d %B %Y %H:%M Uhr", $data->dt);
        }
        
        $content = '
				<div class="weather">
					<div class="innerWrap">
						<h3 class="colored-background">
							Wetter: ' . $data->name . '
							<img height="45" width="45" align="absmiddle" style="border: medium none; width: 45px; height: 45px; background: url(&quot;http://openweathermap.org/img/w/' . $data->weather[0]->icon . '.png&quot;) repeat scroll 0% 0% transparent;" alt="title" src="http://openweathermap.org/images/transparent.png"/>
						</h3>
						<dl>
        ';
        
        foreach ($dataOut as $key => $value) {
          $content .= "<dt>" . $key . "</dt><dd>" . $value . "</dd>";
        }
        
        $content .= '
						</dl>
					</div>
				</div>
				';
      }
    }
    return $content;
  }
  
  /**
   * Write a file
   * @param string $filename
   * @param string $content
   */
  private function _writefile($filename, $content) {
    $handle = fopen($filename, 'w');
    fwrite($handle, $content);
    fclose($handle);
  }
  
  /**
   * Read a file
   * @param string $filename
   */
  private function _readfile($filename) {
    $handle = fopen($filename, "rb");
    $content = fread($handle, filesize($filename));
    fclose($handle);
    return $content;
  }
}

/*
 * make instance, set city and call main-method
 */
$weather = new weather;
$weather->setCity("Berlin");
echo $weather->main();

/*
 * In Web-Frontend you maybe use jQuery:
 * $.get("path/to/weather.php", function (data) {
 *   $("#myWeatherContent").html(data);
 * }, "html");
 */
?>
(1) Jack MacCr4ck schrieb am 6. 8. 2015 um 18:26 Uhr
Funktioniert super, nur dass es bei der Ausgabe immer ein  mit einfügt, wie bekomm ich das weg?

Aktuell:
34° C