PHP实现返回JSON和XML的类分享

yipeiwu_com5年前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实现自动登入google play下载app report的方法

本文实例讲述了PHP实现自动登入google play下载app report的方法,有不错的实用价值。分享给大家供大家参考。具体实现步骤如下: 一、流程: 1.登入google pla...

php之curl实现http与https请求的方法

本文实例讲述了php之curl实现http与https请求的方法,分享给大家供大家参考。具体如下: 通常来说,php的curl函数组可以帮助我们把机器伪装成人的行为来抓取网站,下面来分享...

PHP面向对象程序设计之类与反射API详解

本文实例讲述了PHP面向对象程序设计之类与反射API。分享给大家供大家参考,具体如下: 了解类 class_exists验证类是否存在 <?php // TaskRun...

php简单静态页生成过程

一、用到的相关技术关键词:PHP, Apache,           &n...

php 生成WML页面方法详解

由于静态的WAP页面在很多方面不能满足用户个性化的服务请求,因此通过WAP服务器端语言产生动态的WML页面,具有很广泛的应用价值和很高的商业价值。   WAP应用结构非常类似于Inter...