zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    异步请求模板和数据
    关于线上js报错问题的思考
    标准web浏览器的组件
    监控图片加载的方法
    图片轮播
    jQuery的一些小技巧()
    setTimeout/setInterval伪异步
    linux/windows java jdk环境配置
    iOS pod 第三方 unrecognized selector sent to instance
    上海4
  • 原文地址:https://www.cnblogs.com/jdhu/p/4189312.html
Copyright © 2011-2022 走看看