现在的网站都会有一些服务性的东东。如日历,天气预报等等!
本来想用ajax来实现的!可是ajax是不能调用远程的xml,只能指望动态语言啦!
google天气预报的api:http://www.google.com/ig/api?weather=$city&hl=zh-cn;
<?php
header("content-Type: text/html; charset=Utf-8");
$city = empty($_GET['city']) ? 'shaoguan' : $_GET['city'];
$content =
file_get_contents("http://www.google.com/ig/api?weather=$city&hl=zh-cn");
//$content = mb_convert_encoding($content, 'UTF-8', 'GBK'); //gbk to
utf-8
$content = iconv("GBK", "UTF-8", $content);
$xml = new DOMDocument();
$xml->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 .
"℃<br />";
?>
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写的例子
<?php
$city = empty($_GET['city']) ? 'zhuhai' : $_GET['city'];
$content =
file_get_contents("http://www.google.com/ig/api?weather=$city&hl=zh-cn");
$content || die("No such city's data");
$content = mb_convert_encoding($content, 'UTF-8', 'GBK');
$xml = simplexml_load_string($content);
$date =
$xml->weather->forecast_information->forecast_date->attributes();
$html = $date. "<br>\r\n";
$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,<img
src='http://www.google.com/ig{$icon}'/> {$humidity}{$wind}<br
/>";
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} <img
src='http://www.google.com/ig{$icon}' /><br />";
}
header('Content-type: text/html; Charset: utf-8');
print $html;
?>
php调用google api 开发天气预报
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章