通訊資料的標準格式:
code狀態代碼(200,400等);
message提示資訊(登入失敗,資料返回成功等);
data返回資料;
1、json 方式封裝通訊介面
方法:json_encode($value);
註:該函數只能接受utf-8編碼的資料;如果傳遞其他格式的資料該函數會返回null;
class Response { /** * 按json方式輸出通訊資料* @param int $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;} }
?>
2、xml的方式封裝通訊介面
方法:php產生xml資料;
首先php如何產生xml資料,總結有兩種方法:
1.組裝成xml字串;
2.使用系統類別(DomDocument、XMLWriter、SimpleXML);
class Response { /** * 按xml方式輸出通訊資料* @param int $code 狀態代碼* @param string $message 提示資訊* @param array $data 資料* @return void */public static function xmlEncode(
$code,$message=
'',$data=
array()) {
$r =
'';if(!is_numeric(
$code))
$r =
'';$result =
array(
'code'=>
$code,'message'=>
$message,'data'=>
$data,)
;header(
"Content-Type:text/xml")
;$xml =
"\n";$xml .=
"\n";$xml .=
self::
xmlToEncode(
$result)
;$xml .=
"";$r =
$xml;echo $r;}
public static function xmlToEncode(
$data) {
$xml =
$attr =
"";foreach(
$data as $key=>
$value) {
if(is_numeric(
$key)) {
$attr =
"id='{
$key}
'";$key =
'item';}
$xml .=
"<{
$key} {
$attr}
>";$xml .= is_array(
$value)?
self::
xmlToEncode(
$value):
$value;$xml .=
"{$key}>\n";} return $xml;} }?>
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
以上就介紹了PHP_APP通訊介面—封裝通訊介面的方法,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。