SingWa老师您好~APP接口实例应该是本期最后的课程吧!
好期待以后还有这么实用的课程。老师辛苦了~~
贴上自己写的“综合方式封装通信数据方法”代码,证明自己认真学了而且练习了。
class Response { const JSON = 'json'; public static function show ($code,$message = '',$data = array(),$type = self::JSON) { if (!is_numeric($code)) { return ''; } $result = array( 'code' => $code, 'message' => $message, 'data' => $data ); $type = isset($_GET['format'])?$_GET['format']:self::JSON; if ($type == 'json') { self::json($code,$message,$data); exit; }elseif ($type == 'array') { var_dump($result); }elseif ($type == 'xml') { self::xmlEncode($code,$message,$data); exit; }else { //TO DO } } /* 按json方式输出通信数据 @param integer $code 状态码 @param string $message 提示信息 @param array $data 数据 return string */ public static function json ($code,$message = '',$data = array()) { if(!is_numeric($code)){ return ''; } $result = array( 'code' => $code, 'message' => $message, 'data' => $data ); echo json_encode($result); exit; } public static function xml () { //PHP生成XML数据(采用组装字符串方式) header("Content-type:text/xml"); $xml = "<?xml version='1.0' encoding='UTF-8'?>"; $xml .= "<root>"; $xml .= "<code>200</code>"; $xml .= "<message>数据返回成功</message>"; $xml .= "<data>"; $xml .= "<id>1</id>"; $xml .= "<name>colin</name>"; $xml .= "</data>"; $xml .= "</root>"; echo $xml; } /* 按XML方式输出通信数据 @param integer $code 状态码 @param string $message 提示信息 @param array $data 数据 return string */ public static function xmlEncode ($code, $message = '', $data = array()) { if (!is_numeric($code)) { return ''; } $result = array( 'code' => $code, 'message' => $message, 'data' => $data ); header("Content-type:text/xml"); $xml = "<?xml version='1.0' encoding='UTF-8'?>"; $xml .= "<root>"; $xml .= self::xmlToEncode($result); $xml .= "<code>200</code>"; $xml .= "<message>数据返回成功</message>"; $xml .= "</root>"; echo $xml; } public static function xmlToEncode ($data) { $xml = $arr = ''; foreach ($data as $key=>$val){ if (is_numeric($key)) { //解决xml数据节点不能为数字 $arr = " id='$key'";//<0>56<0> <item id="0">56</item> $key = "item"; } $xml .= "<{$key}{$arr}>"; $xml .= is_array($val) ? self::xmlToEncode($val):$val;//递归判断 $xml .= "</{$key}>"; } return $xml; } } $data = array( 'id' => 1, 'name' => 'colin', 'type' => array(56,57,58) ); Response::show(200,'数据返回成功', $data);