PHP_APP通訊介面—封裝通訊介面的方法

來源:互聯網
上載者:User
通訊資料的標準格式:

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教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.