PHP天气API接口.docx
《PHP天气API接口.docx》由会员分享,可在线阅读,更多相关《PHP天气API接口.docx(19页珍藏版)》请在冰豆网上搜索。
PHP天气API接口
PHP天气API接口
中国天气网的API还每次还要先去判断ID,再获取天气信息,觉得有点麻烦,所以自己做了一个PHP一部搞定的。
还有一个农历API。
php
header('Access-Control-Allow-Origin:
*');
header("Content-Type:
text/javascript;charset=utf-8");
/**
*获取用户真实IP
*/
functiongetIP()
{
static$realip;
if(isset($_SERVER)){
if(isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$realip=$_SERVER["HTTP_X_FORWARDED_FOR"];
}elseif(isset($_SERVER["HTTP_CLIENT_IP"])){
$realip=$_SERVER["HTTP_CLIENT_IP"];
}else{
$realip=$_SERVER["REMOTE_ADDR"];
}
}else{
if(getenv("HTTP_X_FORWARDED_FOR")){
$realip=getenv("HTTP_X_FORWARDED_FOR");
}elseif(getenv("HTTP_CLIENT_IP")){
$realip=getenv("HTTP_CLIENT_IP");
}else{
$realip=getenv("REMOTE_ADDR");
}
}
return$realip;
}
/**
*获取IP地理位置
*淘宝IP接口
*@Return:
array
*/
functiongetCity($ip)
{
$url="
$ip=file_get_contents($url));
if((string)$ip->code=='1'){
returnfalse;
}
$data=$ip->data->city;
return$data;
}
functiongetWeather($cityId)
{
$url="
$weather=file_get_contents($url));
return$weather;
}
function$web){
$arr=array();
foreach($webas$k=>$w){
if(is_object($w))$arr[$k]=$w);//判断类型是不是object
else$arr[$k]=$w;
}
return$arr;
}
$city=getCity(getIP());
$city=str_split($city,strlen($city)-3);
$city=$city[0];
$cityUrl="
$web=file_get_contents($cityUrl));
$arr=$web);
$weatherInfo=getWeather($arr[$city]);
echo('weather(');
echo($weatherInfo));
echo(")");
?
>
城市源码
DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http:
//www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
//www.w3.org/1999/xhtml">
无标题文档