PHP返回JSON和XML类

本文介绍了一个简单的PHP类,该类能够生成标准的XML和JSON格式的响应数据。这个类提供了两个静态方法:json和xml,分别用于创建JSON和XML格式的数据响应。文章通过示例展示了如何使用这两个方法来构造具体的响应数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 string
10          */
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'=>$data
19             );
20             return json_encode($result);
21             exit;
22         }
23         
24         /**
25          * @desc 返回xml格式数据
26          * @parma int $code 状态码
27          * @param string $message 提示
28          * @param array $data 数据
29          * return string 
30          */
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'=>$data
39             );
40             $xml = '';
41             
42             $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;
48 
49          }
50          
51          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}>";
59                 
60                 $xml .= is_array($val) ? self::xmlEncode($val) : $val;
61             
62                 $xml .= "</{$key}>\n";
63             }
64          
65             return $xml;
66          
67          }
68          
69     }
70     
71     $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);

 

转载于:https://www.cnblogs.com/ikasa007/p/4255207.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值