php調用google api 開發天氣預報

現在的網站都會有一些服務性的東東。如日曆,天氣預報等等!
本來想用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;
?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章