[PHP]获取当前天气,基于REST的简单实例.docVIP

  • 3
  • 0
  • 约1.56千字
  • 约 4页
  • 2018-01-04 发布于河南
  • 举报

[PHP]获取当前天气,基于REST的简单实例.doc

[PHP]获取当前天气,基于REST的简单实例

[PHP]获取当前天气,基于REST的简单实例 本例是基于REST架构的Web Service,用于获取某城市的天气情况.(天气数据使用的是google weather api)。 先了解一下REST架构具有的特性:(以下为引用) 统一接口:所有的资源通过统一的接口访问(HTTP GET, POST, PUT, DELETE)) 统一命名:REST系统中的资源(API)必须统一命名和规划,REST系统由使用URI命名的资源组成。REST最大的优势是提出了一个可以对资源和RPC统一命名的URI标准。这难能可贵。 交互形式: 主要以拉(pull)为基础的交互形式,通过长连接实现push。 可以缓冲:提升网络效能,可以将资源(响应)分为可缓存的和不可缓存的。 资源呈现:资源呈现(Resource Representation)允许有不同的表现的形式(text,xml,json,bin,gif,…), 同一RESTful API可以取得不同表现形式的Resource。 分层组件:可以在客户和资源之间插入不同的中间组件来提升性能和安全等,如,代理服务,缓存服务,网关服务等。 无状态:本次连接和下一次到服务器的连接之间没有状态。这在在服务之间需要状态的时候是弊端。如果服务内的状态可以用长连接解决(如聊天服务)。 本例是使用GET方式,返回的资源类型为XML。 服务端代码:(service.php) ?View Code PHP 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 simplexml_load_string($data); header(Content-type: text/xml); echo $xml-asXML(); // 生成XML数据 function createXml($city) { // Google 天气API $weather = simplexml_load_file(/ig/api?weather={$city}); if(isset($weather-weather-forecast_conditions)) { $low = f2c($weather-weather-forecast_conditions-low[data]); $high = f2c($weather-weather-forecast_conditions-high[data]); return {$city} {$low} {$high} ; } else { return ; } } // 华氏度转摄氏度 function f2c($fahrenhite) { return floor(($fahrenhite - 32) / 1.8); } 客户端代码:(client.php) ?View Code PHP 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 天气查询 empty($_POST[city])) { $city = $_POST[city]; $xml = simplexml_load_file(/rest/service.php?city={$city}); $html = City:{$xml-city} ; $html .= Low:{$xml-low} ; $html .= High:{$xml-high} ; echo $html; } ?

文档评论(0)

1亿VIP精品文档

相关文档