浏览量 1
1.调用天气api接口 可以在百度apistore找到免费的api接口
代码语言:javascript复制//天气api
public function getWeather($city){
$ch = curl_init();
$url = 'http://apis.baidu.com/apistore/weatherservice/weather?citypinyin='.$city;
$header = array(
'apikey:你自己的apikey'
);
// 添加apikey到header
curl_setopt($ch, CURLOPT_HTTPHEADER , $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 执行HTTP请求
curl_setopt($ch , CURLOPT_URL , $url);
$res = curl_exec($ch);
//将json转化为php变量
$res=json_decode($res);
return $res;
}
2.获取用户发送过来的数据,并给出回复
代码语言:javascript复制//数据载入对象中
//对象名为SimpleXMLElement
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
//获取天气的json
$result=(array)self::getWeather("$keyword");
$resStr=(array)$result["retData"];
$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>";
$msgType = "text";
//将获取的数组连接成自符串
$contentStr ="城市:".$resStr["city"]."n"."日期:".$resStr["date"]."n"."时间:".$resStr["time"]."n"."天气".$resStr["weather"]."n"."气温:".$resStr["temp"]."n"."最低温度:".$resStr["l_tmp"]."n"."最高温度:".$resStr["h_tmp"]."n"."风向:".$resStr["WD"].$resStr["SD"];
//封装xml并返回给用户
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,$contentStr);
echo $resultStr;