萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php采集自中央氣象台范圍覆蓋全國的天氣預報代碼實例

php采集自中央氣象台范圍覆蓋全國的天氣預報代碼實例

 這篇文章主要介紹了php采集自中央氣象台范圍覆蓋全國的天氣預報代碼實例,較為詳細的分析了采集的技巧及對應接口的調用技巧,具有一定參考借鑒價值,需要的朋友可以參考下

   

本文實例講述了php采集自中央氣象台范圍覆蓋全國的天氣預報代碼。分享給大家供大家參考。具體分析如下:

天氣預報信息采集自中央氣象台,信息准確,覆蓋面廣,代碼簡單,返回是json代碼,可以用於客戶端調用,也可以在服務器端處理後顯示,筆者的wordpress天氣預報插件就是使用的這段代碼,需要注意的是,這段代碼會在服務器產生緩存文件,需要在當前目錄中新建data文件夾,保證文件夾可寫.

php天氣預報代碼如下:

代碼如下: /*
作者: freemouse
主頁: www.cnphp.info
接口demo: http://www.cnphp.info/tianqi
用法: 可以直接調用上面的地址會顯示當地的天氣信息,也可以這樣用
http://www.cnphp.info/tianqi/?q=江蘇省南京市
**/

 

$p = $_get['q'];
$k = 0;
$encoding = mb_detect_encoding($p);
if($encoding != "utf-8"){
$p = mb_convert_encoding($p,"utf-8","gbk");
}
$p_arr = array(
"01" => "北京",
"02" => "上海",
"03" => "天津",
"04" => "重慶",
"05" => "黑龍江",
"06" => "吉林",
"07" => "遼寧",
"08" => "內蒙古",
"09" => "河北",
"10" => "山西",
"11" => "陝西",
"12" => "山東",
"13" => "新疆",
"14" => "西藏",
"15" => "青海",
"16" => "甘肅",
"17" => "寧夏",
"18" => "河南",
"19" => "江蘇",
"20" => "湖北",
"21" => "浙江",
"22" => "安徽",
"23" => "福建",
"24" => "江西",
"25" => "湖南",
"26" => "貴州",
"27" => "四川",
"28" => "廣東",
"29" => "雲南",
"30" => "廣西",
"31" => "海南",
"32" => "香港",
"33" => "澳門",
"34" => "台灣"
);

function find(&$item,$key,$data){
global $k;
if(preg_match("/$item/u",$data)){
$k = $key;
}
}

function get_data_arr($key){
if(!file_exists("./data/city{$key}.xml")){
$c =file_get_contents( "http://m.weather.com.cn/data5/city{$key}.xml" );
file_put_contents("./data/city{$key}.xml",$c);
}
else{
$c = file_get_contents("./data/city{$key}.xml");
}
$arr = explode(",",$c);
foreach($arr as $v){
$data = explode("|",$v);
$ret[$data[0]] = $data[1];
}
return $ret;
}

array_walk($p_arr,'find',$p);
array_walk(get_data_arr($k),'find',$p);
array_walk(get_data_arr($k),'find',$p);
$ccode = get_data_arr($k);
echo file_get_contents("http://m.weather.com.cn/data/{$ccode[$k]}.html");

 

希望本文所述對大家的php程序設計有所幫助。

copyright © 萬盛學電腦網 all rights reserved