php调用google api 开发天气预报

现在的网站都会有一些服务性的东东。如日历,天气预报等等!

本来想用ajax来实现的!可是ajax是不能调用远程的xml,只能指望动态语言啦!

google天气预报的api:http://www.google.com/ig/api?weather=$city&hl=zh-cn

loadXML($content);    

$curr= $xml->getElementsByTagName('current_conditions');

$temp = $curr>getElementsByTagName("temp_c");

/**

* 要获取Title标签的Id属性要分两部走

* 1. 获取title中所有属性的列表也就是$title->item(0)->attributes

* 2. 获取title中id的属性,因为其在第一位所以用item(0)

*

* 小提示:

* 若取属性的值可以用item(*)->nodeValue

* 若取属性的标签可以用item(*)->nodeName

* 若取属性的类型可以用item(*)->nodeType

*/

echo $temp->item(0)->attributes->item(0)->nodeValue . "℃
";

?>

http://www.google.com/ig/api?weather=$city&hl=zh-cn这个接口是gbk编码的!所以这里用到了一些转码的函数

$content = iconv(”GBK”, “UTF-8″, $content);

$content = mb_convert_encoding($content, “UTF-8″, “GBK”);

他们实现的功能都是差不多的!

更多php的帮助请查看

http://cn.php.net/manual/en/function.mb-convert-encoding.php

上面只是一个小小的例子

还要一个用simpleXML写的例子

weather->forecast_information->forecast_date->attributes();

$html = $date. "
rn";

$current = $xml->weather->current_conditions;

$condition = $current->condition->attributes();

$temp_c = $current->temp_c->attributes();

$humidity = $current->humidity->attributes();

$icon = $current->icon->attributes();

$wind=$current->wind_condition->attributes();

$icon && $icon = $xml->weather->forecast_conditions->icon->attributes();

$html.= "当前: {$condition}, {$temp_c}°C, {$humidity}{$wind}
";

foreach($xml->weather->forecast_conditions as $forecast) {

$low = $forecast->low->attributes();

$high = $forecast->high->attributes();

$icon = $forecast->icon->attributes();

$condition = $forecast->condition->attributes();

$day_of_week = $forecast->day_of_week->attributes();

$html.= "{$day_of_week} : {$high} / {$low} °C, {$condition}
";

}

header('Content-type: text/html; Charset: utf-8');

print $html;

?>

[via]

评论

Popular Posts

高硼硅玻璃水杯

《小狗钱钱》[德] 博多·舍费尔

甄果人 原味香葱牛轧饼

新概念英语PDF扫描版

《斗破苍穹》天蚕土豆

CuteHttpFileServer/chfs 文件服务器,支持http,webdav,多平台

MD大战略2 德国闪击战 中文汉化版

MIFARE Classic Tool - 安卓NFC门禁卡修改工具

jamesdonkey贱驴无线蓝牙鼠标