亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

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);


正在回答

1 回答

嗯,不錯,加油,祝學習愉快

0 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消
PHP開發APP接口
  • 參與學習       79157    人
  • 解答問題       608    個

APP通信接口技術,不得不掌握的法寶,學完之后你會受益良多

進入課程
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號