在BAE“开发者服务管理”点击LBS服务,查看应用会看到自己的API。
没有可创建。
2.在左侧“查看服务”,进入“车联网API”,“查看文档”。
“接口说明”,“天气查询”。
得到天气查询地址链接:
http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=yourkey
location:城市名称,经纬度均可;必填
output:默认XML格式,需要传输JSON格式就写上“&output=json”,不需要去掉;非必填
ak:使用应用的密钥。必填
3.点击链接会得到数据文件(在chrome浏览器运行此类链接可查看文件内容)。会提示errmsg错误,就和微信提示自定义菜单格式出错一样。
修改链接:http://api.map.baidu.com/telematics/v3/weather?location=济源&ak=你的ak
4.得到如下XML数据:
按照三角箭头把层次分清楚。
//========================================
代码:$weatherUrl="http://api.map.baidu.com/telematics/v3/weather?location={$keyword}&ak=你的ak";
$apistr = file_get_contents($weatherUrl);
$apiObj = simplexml_load_string($apistr);
$currentcity = $apiObj->results->currentCity; //当前城市
$date1 = $apiObj->results->weather_data->date[0];//今天
$tianqi1 = $apiObj->results->weather_data->weather[0];//今天天气
$wendu1 = $apiObj->results->weather_data->temperature[0];//今天气温
$date2 = $apiObj->results->weather_data->date[1];//明天
$tianqi2 = $apiObj->results->weather_data->weather[1];//明天天气
$wendu2 = $apiObj->results->weather_data->temperature[1];//明天气温
$date3 = $apiObj->results->weather_data->date[2];//后天
$tianqi3 = $apiObj->results->weather_data->weather[2];//后天天气
$wendu3 = $apiObj->results->weather_data->temperature[2];//后天气温
$contentStr1="城市:{$currentcity}\n{$date1},{$tianqi1},{$wendu1};\n";
$contentStr2="{$date2},{$tianqi2},{$wendu2};\n";
$contentStr3="{$date3},{$tianqi3},{$wendu3}。";
$content=$contentStr1.$contentStr2.$contentStr3;
代码说明:
1.$weatherUrl:获取地址。location:用户发送的关键词;ak:这里处于安全没有写,实际操作必须写。
2.$apistr:将获取的文件数据保存到字符串中。
3.$apiObj:解析XML数据字符串,将数据载入到对象中。
以上三步,可触类旁通。
下面请参照XML数据图片理解
4.$currentcity = $apiObj->results->currentCity;
$apiObj就是图片中的“一级”,results“二级”,currentcity是“三级”。——自己画一个树状结构图。
5.$date1 = $apiObj->results->weather_data->date[0]
date[0]由来:首先weather_data是它的父节点,找到date要先找到它的“老爸”——weather_data;
因为有多个date节点,date[0]表示第一个date,date[1]表示第二个date。
名字相同的节点都可以这样表示,下面的天气和温度数据一个道理。