php调用google的天气API,实时显示天气信息。
代码:
<?php
/**
* 显示天气信息
* 文件名:google_weather_api.php
* by www.jb200.com
*/
class weather
{
public static $response;
public static $location;
public static $current;
public static $nextdays;
public static $error = false;
public function weather()
{
$this->location = 'Brasov';
}
public function get()
{
if (empty($this->location)) {
$this->error = true;
return false;
}
$requestAddress = "http://www.google.com/ig/api?weather=".trim(urlencode($this->location))."&hl=en";
$xml_str = file_get_contents($requestAddress,0);
$xml = new SimplexmlElement($xml_str);
if (!$xml->weather->problem_cause) {
$this->response = $xml->weather;
$this->parse();
}else{
$this->error = true;
}
}
public function parse()
{
foreach($this->response as $item) {
$this->current = $item->current_conditions;
foreach($item->forecast_conditions as $new) {
$this->nextdays[] = $new;
}
}
}
public function display()
{
foreach($this->nextdays as $new) {
echo '<div class="weatherIcon">';
echo '<h2>'.$new->day_of_week['data'].'</h2>';
echo '<img src="http://www.google.com/' .$new->icon['data'] . '"/><br/>';
echo '<br />Min: '.$this->convert($new->low['data']).' ℃';
echo '<br />Max: '.$this->convert($new->high['data']).' ℃';
echo '</div>';
}
}
public function convert($value, $unit = "C"){
switch($unit){
case "C":
return number_format(($value - 32)/1.8);
break;
case "F":
return round($value * 1.8 + 32);
break;
default:
return $value;
break;
};
}
}
调用示例:
<?php
require_once('google_weather_api.php');
$weather = new weather();
if (!empty($_GET['loc'])) {
$weather->location = $_GET['loc'];
}
$weather->get();
if($weather->error){
die('We couldn't find your location.');
}else{
echo '
<div id="currentWeather">
<h1>现在是:'.ucwords($weather->location).': '.$weather->current->temp_c['data'].' ℃</h1>
<img src="http://www.google.com/' .$weather->current->icon['data'] . '"/>
<p>'.$weather->current->condition['data'].'</p>
<p>'.$weather->current->humidity['data'].'</p>
<p>'.$weather->current->wind_condition['data'].'</p>
</div>
';
// 显示更多天气信息
// print_r($weather->nextdays);
$weather->display();
}
您可能感兴趣的文章: