標籤:
封裝通訊介面資料方法:
1.json方式封裝資料方法
2.xml方式封裝資料方法
3.綜合資料封裝方法。
json方式:json_encode();
該函數只接受utf-8編碼的資料;
iconv(‘原始編碼‘,‘目標編碼‘,‘變數‘);通過此函數轉換編碼;
xml方式
php產生xml資料:
1>組裝字串
2>使用系統類別
DomDocument
<?php
$dom = new DOMDocument(‘1.0‘,‘utf-8‘);
$element = $dom->createElement(‘test‘,‘This is the root element!‘);
$dom->appendChild($element);
echo $dom->saveXml();
?>
XMLWriter
SimpleXML
xml的節點不能為數字,所以索引數組會報錯;
解決方案:
<0>1</0>
===><item id=‘0‘>1</item>
通訊資料標準格式:
code 狀態代碼(200,400等)
message 提示資訊(郵箱格式不正確,資料返回不成功等)
data 返回資料
<?php
class Response{
/**
*按json方式輸出通訊資料
*@param integert $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
}
return json_encode($result);
}
public static function xml(){
header(‘Content-Type:text/xml‘);
$xml = "<?xml version=‘1.0‘ encoding=‘UTF-8‘?> \n";
$xml.="<root> \n";
$xml.="<code>200</code>\n";
$xml.="<message>資料返回成功</message>\n";
$xml.="<data>\n";
$xml.="<id>1</id>\n";
$xml.="<name>xiaoming</name>\n";
$xml.="</data>\n";
$xml.="</root>";
}
/**
*按xml方式輸出通訊資料
*@param integert $code 狀態代碼
*@param string $message 提示資訊
*@param array $data 資料
*return string
*/
public static function xmlEncode($code,$message=‘‘,$data){
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‘?> \n";
$xml.="<root> \n";
$xml.=self::xmlToEncode($result);
$xml.="</root>";
}
public static function xmlToEncode($data){
$xml=$attr="";
foreach($data as $key=>$value){
if(is_numeric($key)){
$attr="id=‘{$key}‘";
$key="item";
}
$xml.="<{$key}{$attr}>\n";
$xml.=is_array($value)?self::xmlToEncode($value):$value;
$xml.="</{$key}> \n";
}
return $xml;
}
/**
*按綜合方式輸出通訊資料
*@param integert $code 狀態代碼
*@param string $message 提示資訊
*@param array $data 資料
*@param string $type 資料類型
*return string
*/
public static function show($code,$message=‘‘,$data=array(),$type=‘json‘){
if(!is_numeric($code)){
return "";
}
$type=isset($_GET[‘format‘])?$_GET[‘format‘]:$type;
$result=array(
‘code‘ => $code,
‘message‘ => $message,
‘data‘ => $data
)
if($type == ‘json‘){
self::json($code,$message,$data);
exit;
}elseif($type == ‘array‘){
return $result;
}elseif($type == ‘xml‘){
self::xmlEncode($code,$message,$data);
}else{
//TODO
}
}
}
?>
=================================================================
<?php
/*直接調用*/
require_once(‘./reponse.php‘);
$arr = array{
‘id‘ =>1,
‘name‘ => ‘xiaoming‘
)
Reponse::json(200,‘資料返回成功‘,$arr);
Reponse::xmlEncode(200,‘資料返回成功‘,$arr);
?>
PHP開發APP介面(三)