• PHP开发APP接口---返回数据的封装类


    参考视频http://www.imooc.com/learn/163

    <?php 
    
    /**
    * app返回数据类
    * 1.接受多维,缺少键名的数组,
    * 2.可由输入的format参数决定返回数据格式
    * 例子:Response::show(200, 'success', $data);
    */
    class Response
    {
        const JSON = 'json';
    
        /**
         * 按json格式输出通信数据
         */
        public static function json($result)
        {
            echo json_encode($result);
        }
    
        /**
         * encode XML的数据部分
         */
        private static function _xml_encode($data)
        {
            $xml = "";
            foreach ($data as $key => $value) {
    
                //如果键名是数字,则改为<item id="0"></item>格式
                $attr = '';
                if (is_numeric($key)) {
                    $attr = " id='{$key}'";
                    $key = "item";
                }
    
                //如果键值是数组,则递归调用自己
                $xml .= "<{$key}{$attr}>";
                $xml .= is_array($value) ? "
    " . self::_xml_encode($value) : $value;
                $xml .= "</{$key}>
    ";
            }
    
            return $xml;
        }
    
        /**
         * 按xml格式输出通信数据
         */
        public static function xml($result) 
        {
            header("Content-Type:text/xml");
            $xml = "<?xml version='1.0' encoding='UTF-8'?>
    ";
            $xml .= "<root>
    ";
    
            $xml .= self::_xml_encode($result);
    
            $xml .= "</root>
    ";
    
            echo $xml;
        }
    
        /**
         * 按输入的格式输出通信数据
         */
        public static function show($code, $message = "", $data = array(), $type = self::JSON) 
        {
            if ( ! is_numeric($code)) {
                die('json输入参数需要数字');
            }
    
            //如果存在请求的格式化类型
            $type = isset($_GET['format']) ? $_GET['format'] : $type;
    
            $result = array(
                'code' => $code,
                'message' => $message,
                'data' => $data,
            );
    
            if ($type == 'json') {
                self::json($result);
            }
            elseif($type == 'xml') {
                self::xml($result);
            }        
            elseif($type == 'array') {
                echo '<pre>';
                print_r($result);
                echo '</pre>';
            }
            exit;
        }
    
    }
    
    //可多维,缺少键名的数组,可由输入的format参数决定返回数据格式
    $data = array(
        'id' => 1,
        'name' => 'haha',
        'addr' => array(1,2,3=>array(22,'hh')),
    );
    
    Response::show(200, 'success', $data);
     ?>

    结果如下:

    image

  • 相关阅读:
    设置共享文件夹大小
    About IConfigurationSectionHandler Interface
    zoj 1050
    SQL Server 数据库优化经验总结
    一、页面输出缓存
    [转]深入解读 ADO.NET 2.0 的十大最新特性
    ASP.NET 缓存学习
    [转]写给ASP.NET程序员:网站中的安全问题
    [转] ASP.NET 性能提升秘诀之管道与进程优化
    实战 SQL Server 2005 镜像配置
  • 原文地址:https://www.cnblogs.com/jdhu/p/4189312.html
Copyright © 2020-2023  润新知