PHP返回JSON和XML類

來源:互聯網
上載者:User

標籤:

 1 <?php 2     class Reponse{ 3         //private $result = array(‘code‘=null,‘message‘=null,‘data‘=>null); 4         /** 5          * @desc 返回JSON格式 6          * @param int $code 7          * @param string $message 8          * @param array  $data 9          * return string10          */11         public static function json($code,$message = null,$data = array()){12             if(!is_numeric($code)){13                 return false;14             }15             $result = array(16                 ‘code‘=>$code,17                 ‘message‘=>$message,18                 ‘data‘=>$data19             );20             return json_encode($result);21             exit;22         }2324         /**25          * @desc 返回xml格式資料26          * @parma int $code 狀態代碼27          * @param string $message 提示28          * @param array $data 資料29          * return string30          */31          public static function xml($code,$message = ‘‘,$data = array()){32             if(!is_numeric($code)){33                 return false;34             }35             $result = array(36                 ‘code‘=>$code,37                 ‘message‘=>$message,38                 ‘data‘=>$data39             );40             $xml = ‘‘;4142             $xml .= "<?xml version=‘1.0‘ encoding=‘UTF-8‘?>\n";43             $xml .= "<root>\n";44             $xml .= self::xmlEncode($result);45             $xml .= "</root>";46             header("Content-Type:text/xml");47             echo $xml;4849          }5051          public static function xmlEncode($result){52             $xml = $attr =‘‘;53             foreach($result as $key=>$val){54                 if(is_numeric($key)){55                     $attr = "id=‘{$key}‘";56                     $key = "item{$key}";57                 }58                 $xml .= "<{$key} {$attr}>";5960                 $xml .= is_array($val) ? self::xmlEncode($val) : $val;6162                 $xml .= "</{$key}>\n";63             }6465             return $xml;6667          }6869     }7071     $data = array(72         ‘id‘=>1,73         ‘age‘=>20,74         ‘username‘=>‘tim‘,75         ‘others‘=>array(1,2,3),76     );77     Reponse::xml(200,‘success‘,$data);78     Reponse::json(200,‘success‘,$data);

 

原文連結:http://www.faceye.net/search/1261.html

PHP返回JSON和XML類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.