《PHP應用:PHP實現返回JSON和XML的類分享》要點:
本文介紹了PHP應用:PHP實現返回JSON和XML的類分享,希望對您有用。如果有疑問,可以聯系我們。
PHP教程代碼很簡潔,功能也很簡單實用,這里就不多廢話了,直接奉上代碼:
代碼如下:
<?php
??? class Reponse{
??????? //private $result = array('code'=null,'message'=null,'data'=>null);
??????? /**
???????? * @desc 返回JSON格式
???????? * @param int $code
???????? * @param string $message
???????? * @param array? $data
???????? * return string
???????? */
??????? public static function json($code,$message = null,$data = array()){
??????????? if(!is_numeric($code)){
??????????????? return false;
??????????? }
??????????? $result = array(
??????????????? 'code'=>$code,
??????????????? 'message'=>$message,
??????????????? 'data'=>$data
??????????? );
??????????? return json_encode($result);
??????????? exit;
??????? }
??????? /**
???????? * @desc 返回xml格式數據
???????? * @parma int $code 狀態碼
???????? * @param string $message 提示
???????? * @param array $data 數據
???????? * return string
???????? */
???????? public static function xml($code,$message = '',$data = array()){
??????????? if(!is_numeric($code)){
??????????????? return false;
??????????? }
??????????? $result = array(
??????????????? 'code'=>$code,
??????????????? 'message'=>$message,
??????????????? 'data'=>$data
??????????? );
??????????? $xml = '';
??????????? $xml .= "<?xml version='1.0' encoding='UTF-8'?>\n";
??????????? $xml .= "<root>\n";
??????????? $xml .= self::xmlEncode($result);
??????????? $xml .= "</root>";
??????????? header("Content-Type:text/xml");
??????????? echo $xml;
???????? }
???????? public static function xmlEncode($result){
??????????? $xml = $attr ='';
??????????? foreach($result as $key=>$val){
??????????????? if(is_numeric($key)){
??????????????????? $attr = "id='{$key}'";
??????????????????? $key = "item{$key}";
??????????????? }
??????????????? $xml .= "<{$key} {$attr}>";
??????????????? $xml .= is_array($val) ? self::xmlEncode($val) : $val;
??????????????? $xml .= "</{$key}>\n";
??????????? }
??????????? return $xml;
???????? }
??? }
??? $data = array(
??????? 'id'=>1,
??????? 'age'=>20,
??????? 'username'=>'tim',
??????? 'others'=>array(1,2,3),
??? );
??? Reponse::xml(200,'success',$data);
??? Reponse::json(200,'success',$data);
PHP教程小伙伴們可以直接拿去使用,使用辦法在代碼的最下方:)
《PHP應用:PHP實現返回JSON和XML的類分享》是否對您有啟發,歡迎查看更多與《PHP應用:PHP實現返回JSON和XML的類分享》相關教程,學精學透。維易PHP學院為您提供精彩教程。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/12505.html