SingWa老師您好~APP接口實(shí)例應(yīng)該是本期最后的課程吧!
好期待以后還有這么實(shí)用的課程。老師辛苦了~~
貼上自己寫的“綜合方式封裝通信數(shù)據(jù)方法”代碼,證明自己認(rèn)真學(xué)了而且練習(xí)了。
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方式輸出通信數(shù)據(jù) @param integer $code 狀態(tài)碼 @param string $message 提示信息 @param array $data 數(shù)據(jù) 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數(shù)據(jù)(采用組裝字符串方式) header("Content-type:text/xml"); $xml = "<?xml version='1.0' encoding='UTF-8'?>"; $xml .= "<root>"; $xml .= "<code>200</code>"; $xml .= "<message>數(shù)據(jù)返回成功</message>"; $xml .= "<data>"; $xml .= "<id>1</id>"; $xml .= "<name>colin</name>"; $xml .= "</data>"; $xml .= "</root>"; echo $xml; } /* 按XML方式輸出通信數(shù)據(jù) @param integer $code 狀態(tài)碼 @param string $message 提示信息 @param array $data 數(shù)據(jù) 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>數(shù)據(jù)返回成功</message>"; $xml .= "</root>"; echo $xml; } public static function xmlToEncode ($data) { $xml = $arr = ''; foreach ($data as $key=>$val){ if (is_numeric($key)) { //解決xml數(shù)據(jù)節(jié)點(diǎn)不能為數(shù)字 $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,'數(shù)據(jù)返回成功', $data);
2014-08-14
嗯,不錯(cuò),加油,祝學(xué)習(xí)愉快