php获取天气
❶ php获取天气预报的代码
<?php
$URLStyle="http://flash.weather.com.cn/wmaps/xml/%s.xml";
$chinaURL=sprintf($URLStyle,"china");
$chinaStr=file_get_contents($chinaURL);
$chinaObj=simplexml_load_string($chinaStr);
$chinaObjLen=count($chinaObj->city);
echo"chinaObjLen=".$chinaObjLen." ";
for($i=0;$i<$chinaObjLen;$i++){
//遍历省一级节点,共37个
$level1=$chinaObj->city[$i]["pyName"];
$shengjiURL=sprintf($URLStyle,$level1);
$shengjiStr=file_get_contents($shengjiURL);
//echo$shengjiStr;
$shengjiObj=simplexml_load_string($shengjiStr);
$shengjiObjLen=count($shengjiObj->city);
//echo$chinaObj->city[$i]["quName"];
//echo"".$shengjiObjLen." ";
for($j=0;$j<$shengjiObjLen;$j++){
//遍历市一级节点
$level2=$shengjiObj->city[$j]["pyName"];
$shijiURL=sprintf($URLStyle,$level2);
$shijiStr=file_get_contents($shijiURL);
//echo$shijiStr;
$shijiObj=simplexml_load_string($shijiStr);
//直辖市和海南、台湾、钓鱼岛等没有县级节点
if(!$shijiObj){
echo"WARNNING:notexsitnextlevelnode.-".$level1."-".$shijiURL." ";
echo'"'.$shengjiObj->city[$j]["cityname"].'"=>';
echo$shengjiObj->city[$j]["url"].", ";
continue;
}
$shijiObjLen=count($shijiObj->city);
//echo$shengjiObj->city[$j]["cityname"]."";
//echo$shijiObjLen." ";
for($k=0;$k<$shijiObjLen;$k++){
//遍历县一级节点
$xianji_code=$shijiObj->city[$k]["url"];
echo'"'.$shijiObj->city[$k]["cityname"].'"=>';
echo$shijiObj->city[$k]["url"].", ";
//echo$xianji_code." ";
}
}
}
//print_r($chinaObj);
?>
通过XML接口根节点递归获得全国几千个县以上城市cide code的代码
❷ 现在可用的天气API还有哪些新浪外,要PHP可用,最好有实例。
支持直接jsonp调用 腾讯的 :
http://sou.qq.com/online/get_weather.php?callback=Weather&city=nanjing(这个很好 直接输入天气名字就行 英文中文都行)
中国天气http://-weather.com.cn (先查城市id 再查天气)
http://61.4.185.48:81/g/ (根据IP查询城市ID)
http://m.weather.com.cn/data/101110101.html(六天预报)
http://www.weather.com.cn/data/sk/101110101.html(实时天气信息)
❸ 怎样用php获取用户浏览器,操作系统,本地天气
$_SERVER['HTTP_USER_AGENT'] 可以获取用户的操作系统和浏览器
不过客户端传过来的数据,用户可以伪造获取天气得调用别人的接口,新浪,中国气象网都提供接口,你调用就可以了!
❹ 如何使用PHP调用API接口实现天气查询功能
最近在做微信公众平台测试时,想在里面子菜单上添加查询未来几天(包括今天)天气的功能,就查找了下好用的天气预报查询接口API,使用比较多的有:国家气象局天气接口、新浪天气预报接口、网络天气预报接口、google天气接口、Yahoo天气接口等等,我使用的是网络提供的免费天气查询接口API,下面与大家分享下...
1、查询方式:
网络提供的是根据纬度和城市名查询天气情况
2、接口事例:
❺ 怎样用php获取用户浏览器,操作系统,本地天气
$_SERVER['HTTP_USER_AGENT'] 可以获取用户的操作系统和浏览器,不过客户端传过来的数据,用户可以伪造
获取天气得调用别人的接口,新浪,中国气象网都提供接口,你调用就可以了
❻ PHP 页面调用天气预报web服务 我想在一个PHP页面直接调用现成的webservice
完全可以。前提是要打开soap扩展,调用方法如下:
<?php
$client = new SoapClient('http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl');
$parm=array('theCityCode'=>'三亚','theUserID'=>'');
$result=$client->getWeather($parm);
print_r($result);
?>
❼ 怎样用php自动在24点时将天气情况加入数据库
找一段天气预报代码,将返回的json代码通过连接语句插入到数据库中。
然后每天24点定时访问这个php链接就可以了。
❽ 公共平台没开发怎样可以有天气预报
在这篇教程中,我们将介绍如何在微信公众平台上开发天气预报功能。我们将使用中国天气网的气象数据接口来获取天气信息。
这篇教程将介绍以下内容:
获取中国天气网的气象数据
在微信公众平台中回复天气
一、中国天气网
中国天气网提供了丰富的气象数据接口。下面我们介绍主要的几个:
国家根节点接口:
http://flash.weather.com.cn/wmaps/xml/china.xml
该接口以XML格式列出所有的省(自治区、直辖市)的中文名称(quName)和拼音名称(pyName)及省会城市的天气信息,其中广东的数据如下:
<city quName="广东" pyName="guangdong" cityname="广州" state1="2" state2="7" stateDetailed="阴转小雨" tem1="8" tem2="15" windState="微风"/>
该接口的主要功能是通过它获取省级节点的拼音名称。以广东为例:其pyName是“Guangdong”。
省级节点接口(以广东为例):
http://flash.weather.com.cn/wmaps/xml/Guangdong.xml
该接口以XML格式列出当前省下辖所有市的中文名称(quName)、拼音名称(pyName)、中心坐标、天气信息以及城市编码。其中深圳的数据如下所示:
<city cityX="409" cityY="257" cityname="深圳" centername="深圳" fontColor="FFFFFF" pyName="shenzhen" state1="1" state2="1" stateDetailed="多云" tem1="12" tem2="18" temNow="12" windState="微风" windDir="东北风" windPower="1级" humidity="74%" time="21:15" url="101280601"/>
在这个接口中主要获取城市名称及相应的城市编码。例如,深圳的城市编码为:101280601。可以编写程序将全国城市拓扑结构采集下来。也可以使用方倍工作室已经采集好的,点击这里下载。
实时天气数据(以深圳为例):
http://www.weather.com.cn/data/sk/101280601.html
该接口以JSON格式列出当前城市的实时天气状况。如下所示:
{
"weatherinfo": {
"city": "深圳",
"cityid": "101280601",
"temp": "12",
"WD": "东北风",
"WS": "1级",
"SD": "75%",
"WSE": "1",
"time": "21:20",
"isRadar": "1",
"Radar": "JC_RADAR_AZ9755_JB"
}
}
实时天气数据参数说明下所示:
六日天气数据(以深圳为例):
http://m.weather.com.cn/data/101280601.html
该接口以JSON格式列出当前城市的六日天气状况。如下所示:
{
"weatherinfo": {
"city": "深圳",
"city_en": "shenzhen",
"date_y": "2014年2月15日",
"date": "",
"week": "星期六",
"fchh": "18",
"cityid": "101280601",
"temp1": "12℃~18℃",
"temp2": "16℃~21℃",
"temp3": "17℃~23℃",
"temp4": "11℃~18℃",
"temp5": "10℃~15℃",
"temp6": "12℃~17℃",
"tempF1": "53.6℉~64.4℉",
"tempF2": "60.8℉~69.8℉",
"tempF3": "62.6℉~73.4℉",
"tempF4": "51.8℉~64.4℉",
"tempF5": "50℉~59℉",
"tempF6": "53.6℉~62.6℉",
"weather1": "多云",
"weather2": "阴",
"weather3": "多云",
"weather4": "中雨",
"weather5": "多云",
"weather6": "阴",
"img1": "1",
"img2": "99",
"img3": "2",
"img4": "99",
"img5": "1",
"img6": "99",
"img7": "8",
"img8": "99",
"img9": "1",
"img10": "99",
"img11": "2",
"img12": "99",
"img_single": "1",
"img_title1": "多云",
"img_title2": "多云",
"img_title3": "阴",
"img_title4": "阴",
"img_title5": "多云",
"img_title6": "多云",
"img_title7": "中雨",
"img_title8": "中雨",
"img_title9": "多云",
"img_title10": "多云",
"img_title11": "阴",
"img_title12": "阴",
"img_title_single": "多云",
"wind1": "微风",
"wind2": "微风",
"wind3": "微风",
"wind4": "东北风3-4级",
"wind5": "微风",
"wind6": "微风",
"fx1": "微风",
"fx2": "微风",
"fl1": "小于3级",
"fl2": "小于3级",
"fl3": "小于3级",
"fl4": "3-4级",
"fl5": "小于3级",
"fl6": "小于3级",
"index": "较舒适",
"index_d": "建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物,宜着夹克衫、薄毛衣等。",
"index48": "较舒适",
"index48_d": "建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物,宜着夹克衫、薄毛衣等。",
"index_uv": "最弱",
"index48_uv": "最弱",
"index_xc": "适宜",
"index_tr": "适宜",
"index_co": "舒适",
"st1": "19",
"st2": "13",
"st3": "23",
"st4": "16",
"st5": "24",
"st6": "18",
"index_cl": "适宜",
"index_ls": "适宜",
"index_ag": "不易发"
}
}
未来六日天气数据主要参数说明如下表所示:
以上接口是我们做天气预报功能将使用到的接口。
二、微信公众平台开发
1. 需要将城市编码对照表导入到数据库中,以下是SAE导入后截图
2. 将城市名转为城市代码的方法,这将在用户发送城市名的时候调用
1 function fromNameToCode($name)
2 {
3 $mysql_host = SAE_MYSQL_HOST_M;
4 $mysql_host_s = SAE_MYSQL_HOST_S;
5 $mysql_port = SAE_MYSQL_PORT;
6 $mysql_user = SAE_MYSQL_USER;
7 $mysql_password = SAE_MYSQL_PASS;
8 $mysql_database = SAE_MYSQL_DB;
9
10 $mysql_table = "weather";
11 $mysql_state = "SELECT * FROM ".$mysql_table." WHERE `cityName` = '".$name."'";
12
13 $con = mysql_connect($mysql_host.':'.$mysql_port, $mysql_user, $mysql_password, true);
14 if (!$con){
15 die('Could not connect: ' . mysql_error());
16 }
17 mysql_query("SET NAMES 'UTF8'");
18 mysql_select_db($mysql_database, $con);
19 $result = mysql_query($mysql_state);
20 $cityCode = "";
21 while($row = mysql_fetch_array($result))
22 {
23 $cityCode = $row['cityCode'];
24 break;
25 }
26 mysql_close($con);
27 return $cityCode;
28 }
3. 编写接口调用函数,用于向天气网发送cURL请求,获取数据
1 function httpRequest($url)
2 {
3 $ch = curl_init();
4 curl_setopt($ch, CURLOPT_URL, $url);
5 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
6 $output = curl_exec($ch);
7 curl_close($ch);
8 if ($output === FALSE){
9 return "cURL Error: ". curl_error($ch);
10 }
11 return $output;
12 }
4. 编写获取天气数据的函数,这里获取实时天气和未来3日天气,并将返回结果封装成图文信息的数组
1 function getWeatherInfo($cityName)
2 {
3 $cityCode = fromNameToCode($cityName);
4
5 if ($cityCode == "")
6 {
7 return "错误的城市名或者此城市不在数据库中!";
8 }
9
10 //获取实时天气
11 $url = "http://www.weather.com.cn/data/sk/".$cityCode.".html";
12 $output = httpRequest($url);
13 $weather = json_decode($output, true);
14 $info = $weather['weatherinfo'];
15
16 $weatherArray = array();
17 $weatherArray[] = array("Title"=>$info['city']."天气预报", "Description"=>"", "PicUrl"=>"", "Url" =>"");
18 if ((int)$cityCode < 101340000){
19 $result = "实况 温度:".$info['temp']."℃ 湿度:".$info['SD']." 风速:".$info['WD'].$info['WSE']."级";
20 $weatherArray[] = array("Title"=>str_replace("%", "﹪", $result), "Description"=>"", "PicUrl"=>"", "Url" =>"");
21 }
22
23 //获取六日天气
24 $url = "http://m.weather.com.cn/data/".$cityCode.".html";
25 $output = httpRequest($url);
26 $weather = json_decode($output, true);
27 $info = $weather['weatherinfo'];
28
29 if (!empty($info['index_d'])){
30 $weatherArray[] = array("Title" =>$info['index_d'], "Description" =>"", "PicUrl" =>"", "Url" =>"");
31 }
32
33 $weekArray = array("日","一","二","三","四","五","六");
34 $maxlength = 3;
35 for ($i = 1; $i <= $maxlength; $i++) {
36 $offset = strtotime("+".($i-1)." day");
37 $subTitle = date("m月d日",$offset)." 周".$weekArray[date('w',$offset)]." ".$info['temp'.$i]." ".$info['weather'.$i]." ".$info['wind'.$i];
38 $weatherArray[] = array("Title" =>$subTitle, "Description" =>"", "PicUrl" =>"http://discuz.comli.com/weixin/weather/"."d".sprintf("%02u",$info['img'.(($i *2)-1)]).".jpg", "Url" =>"");
39 }
40
41 return $weatherArray;
42 }
5. 在微信公众平台接口函数中处理收到的文本消息时,文本将为城市名,直接调用获取天气的函数
1 /*
2 方倍工作室
3 CopyRight 2013 All Rights Reserved
4 */
5
6 define("TOKEN", "weixin");
7
8 $wechatObj = new wechatCallbackapiTest();
9 if (!isset($_GET['echostr'])) {
10 $wechatObj->responseMsg();
11 }else{
12 $wechatObj->valid();
13 }
14
15 class wechatCallbackapiTest
16 {
17 public function valid()
18 {
19 $echoStr = $_GET["echostr"];
20 if($this->checkSignature()){
21 echo $echoStr;
22 exit;
23 }
24 }
25
26 private function checkSignature()
27 {
28 $signature = $_GET["signature"];
29 $timestamp = $_GET["timestamp"];
30 $nonce = $_GET["nonce"];
31 $token = TOKEN;
32 $tmpArr = array($token, $timestamp, $nonce);
33 sort($tmpArr);
34 $tmpStr = implode($tmpArr);
35 $tmpStr = sha1($tmpStr);
36
37 if($tmpStr == $signature){
38 return true;
39 }else{
40 return false;
41 }
42 }
43
44 public function responseMsg()
45 {
46 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
47 if (!empty($postStr)){
48 $this->logger("R ".$postStr);
49 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
50 $RX_TYPE = trim($postObj->MsgType);
51
52 switch ($RX_TYPE)
53 {
54 case "event":
55 $result = $this->receiveEvent($postObj);
56 break;
57 case "text":
58 $result = $this->receiveText($postObj);
59 break;
60 }
61 $this->logger("T ".$result);
62 echo $result;
63 }else {
64 echo "";
65 exit;
66 }
67 }
68
69 private function receiveEvent($object)
70 {
71 $content = "";
72 switch ($object->Event)
73 {
74 case "subscribe":
75 $content = "欢迎关注方倍工作室 ";
76 break;
77 case "unsubscribe":
78 $content = "取消关注";
79 break;
80 }
81 $result = $this->transmitText($object, $content);
82 return $result;
83 }
84
85 private function receiveText($object)
86 {
87 $keyword = trim($object->Content);
88
89 include("weather.php");
90 $content = getWeatherInfo($keyword);
❾ php怎么抓取天气预报
可以借由php的api或者preg_match_all偷偷撷取去达成目的
这里给你一段我给台湾朋友有一段源码
<?php
header("Content-Type:text/html;charset=utf-8");
functiongetWeather($city){
$toURL="
$city.htm";
$post=array();
$ch=curl_init();
$options=array(
CURLOPT_REFERER=>'',
CURLOPT_URL=>$toURL,
CURLOPT_VERBOSE=>0,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_USERAGENT=>"Mozilla/4.0(compatible;)",
CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=>http_build_query($post),
);
curl_setopt_array($ch,$options);
$result=curl_exec($ch);
curl_close($ch);
//连接中央气象局
echo'<pre>';
preg_match_all('/<tableclass="FcstBoxTable01"[^>]*[^>]*>(.*)</div>/si',$result,$matches,PREG_SET_ORDER);
preg_match_all('/<tdnowrap="nowrap"[^>]*[^>]*>(.*)</td>/si',$matches[0][1],$m1,PREG_SET_ORDER);
$m2=explode('</td>',$m1[0][1]);
//print_r($m2);//取得每日资料m2[0~6]
$weather=array();
for($i=0;$i<=6;$i++){
preg_match_all('/src=[^>]*[^>](.*)/si',$m2[$i],$m5,PREG_SET_ORDER);//取得天气图档
$m6=explode('"',$m5[0][0]);
$wi='
($m6[1],'../../');
$wtitle=$m6[3];
print_r($wtitle);
$weather[$i]['date']=date("m-d",mktime(0,0,0,date("m"),date("d")+$i,date("Y")));
$weather[$i]['temperature']=trim(strip_tags($m2[$i]));
$weather[$i]['title']=$wtitle;
$weather[$i]['img']=$wi;
}
return($weather);
}
$weather=getWeather("Taipei_City");
print_r($weather);
//header("Location:loc.php");
?>
首先
$toURL="http://www.cwb.gov.tw/V7/forecast/taiwan/inc/city/$city.htm";
这里是读取资料的网址
上面的是台湾中央气象局
preg_match_all('/<tableclass="FcstBoxTable01"[^>]*[^>]*>(.*)</div>/si',$result,$matches,PREG_SET_ORDER);
preg_match_all('/<tdnowrap="nowrap"[^>]*[^>]*>(.*)</td>/si',$matches[0][1],$m1,PREG_SET_ORDER);
这里是截取台湾中央气象局网页信息table class="FcstBoxTable01" [^>]*[^>]*>(.*)</div>的资料以及<td nowrap="nowrap" [^>]*[^>]*>(.*)</td>的资料分别是1天跟1周
$m2=explode('</td>',$m1[0][1]);
//print_r($m2);//取得每日资料m2[0~6]
这里是取得每日的资料
preg_match_all('/src=[^>]*[^>](.*)/si',$m2[$i],$m5,PREG_SET_ORDER);//取得天气图档
这里是取得天气的图档
$m6=explode('"',$m5[0][0]);
$wi='
($m6[1],'../../');
$wtitle=$m6[3];
print_r($wtitle);
$weather[$i]['date']=date("m-d",mktime(0,0,0,date("m"),date("d")+$i,date("Y")));
$weather[$i]['temperature']=trim(strip_tags($m2[$i]));
$weather[$i]['title']=$wtitle;
$weather[$i]['img']=$wi;
这里是返回的网址,日期,标题,图档等等的资料
$weather=getWeather("Taipei_City");
print_r($weather);
然后这里是显示出地区的一周天气预报
结论:就是如果你想从网站上面截取天气预报
在php可以是用preg_match_all(网页的表格table,表格的列数tr,表格的栏位td,或者更加广泛的标签div等等获取)
❿ php的socket调用可以实现查天气吗
本文分享下,php调用yahoo与sina的天气api,实现实时显示天气预报的代码,有兴趣的朋友研究下吧。
yahoo 天气预报
地址 http://developer.yahoo.com/weather/
代码:
复制代码代码示例:
<?php
header ( 'Content-Type: text/html; charset = utf-8' );
class weather {
static $url = 'http://xml.weather.yahoo.com/forecastrss?u=c&w=';
static $city = 'Beijing'; //默认城市北京 这里要注意的是 city 要填拼音 我试过用中文有好几个地区都调用不到
static $weatherXML = '';
static $woeid_file = "woeid";
static $file_path = "data/";
/**
* 获得远程xml并缓存到本地
*/
static public function getXML($city = null) {
if ($city != null){
self::$city = $city;
}
self::$weatherXML = self::$file_path . md5(self::$city) . '-weather.xml';
if (file_exists( self::$weatherXML )) {
$fileTime = filemtime ( self::$weatherXML );
$stater = time () - $fileTime - 60 * 60 * 2;
if ($stater > 0) {
return true;
}
}
//获取woeid
$woeid = self::getWOEID();
self::$url = self::$url . $woeid[0];
//获取当天 天气
$XML = self::vget(self::$url);
//保存当天 天气到文件
self::cacheXML($XML);
self::analysisXML($XML);
}
static public function analysisXML($simple) {
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
//本周天气
$weekindex = $index['YWEATHER:FORECAST'];
$week = array();
foreach($weekindex as $k=>$v){
$week[$k] = $vals[$v]['attributes'];
}
unset($index);
unset($vals);
print_r($week);
/*
<yweather:forecast day="Wed" date="18 Sep 2013" low="20" high="32" text="Sunny" code="32"/>
* day 星期
* date 日期
* low 最低温度
* high 最高温度
* test 天气状态
* code 天气图标
*/
}
/*
* 取得地区WOEID码
*/
static private function getWOEID(){
static $woeid = array();
if(isset($woeid[self::$city])){
return $woeid[self::$city];
}
if (file_exists( self::$file_path . self::$woeid_file )) {
$woeidSTR = file_get_contents(self::$file_path . self::$woeid_file);
$woeid = json_decode($woeidSTR , true);
if(isset($woeid[self::$city])){
return $woeid[self::$city];
}
}
$geoPlaces = "http://query.yahooapis.com/v1/public/yql?q=select%20woeid%20from%20geo.places%20where%20text='".self::$city."%20CH'";
$XML = simplexml_load_file( $geoPlaces );
if(isset($XML->results->place[0])){
$rs = $woeid[self::$city] = $XML->results->place[0]->woeid;
//保存到文件
$woeidSTR = json_encode($woeid);
file_put_contents(self::$file_path . self::$woeid_file, $woeidSTR);
return $rs;
}else{
//如果找不到城市 woeid 默认城市就改为 北京
self::$city = "Beijing";
return self::getWOEID();
}
}
/**
* 创建xml缓存
* @param $contents 要缓存的内容
*/
static private function cacheXML($contents) {
$contents = str_ireplace ( '<?xml version="1.0"?>', "<?xml version=\"1.0\"?> \n", $contents );
$contents = mb_convert_encoding ( $contents, 'utf-8', 'gbk' );
file_put_contents ( self::$weatherXML, $contents ) or die ( '没有写权限' );
}
/**
* 模拟获取内容函数
* @param type $url
* @return type
*/
static private function vget($url) {
$user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
$curl = curl_init (); // 启动一个CURL会话
curl_setopt ( $curl, CURLOPT_URL, $url ); // 要访问的地址
curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, 0 ); // 对认证证书来源的检查
curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 1 ); // 从证书中检查SSL加密算法是否存在
curl_setopt ( $curl, CURLOPT_USERAGENT, $user_agent ); // 模拟用户使用的浏览器
@curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 ); // 使用自动跳转
curl_setopt ( $curl, CURLOPT_AUTOREFERER, 1 ); // 自动设置Referer
curl_setopt ( $curl, CURLOPT_HTTPGET, 1 ); // 发送一个常规的Post请求
curl_setopt ( $curl, CURLOPT_TIMEOUT, 120 ); // 设置超时限制防止死循环
curl_setopt ( $curl, CURLOPT_HEADER, 0 ); // 显示返回的Header区域内容
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec ( $curl ); // 执行操作
if (curl_errno ( $curl )) {
curl_close ( $curl ); // 关闭CURL会话
die('Errno' . curl_error ( $curl )) ;
}
curl_close ( $curl ); // 关闭CURL会话
return $tmpInfo; // 返回数据
}
}
weather::getXML("Changsha");