php调用google天气api的实例代码

发布时间:2020-02-02编辑:脚本学堂
本文介绍下,php实现的调用google天气API,实时显示天气预报信息的一个类,有需要的朋友,可以参考学习下。

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']).' &#8451;';
                echo '<br />Max: '.$this->convert($new->high['data']).' &#8451;';
            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'].' &#8451;</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();
}
您可能感兴趣的文章:
php 天气预报代码一例
php调用yahoo sina api天气预报的实现代码
Google API 获取当前天气信息的php代码