码迷,mamicode.com
首页 > 移动开发 > 详细

APP接口返回数据的封装类

时间:2014-12-27 22:55:55      阅读:1043      评论:0      收藏:0      [点我收藏+]

标签:

参考视频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) ? "\n" . self::_xml_encode($value) : $value;
            $xml .= "</{$key}>\n";
        }

        return $xml;
    }

    /**
     * 按xml格式输出通信数据
     */
    public static function xml($result) 
    {
        header("Content-Type:text/xml");
        $xml = "<?xml version=‘1.0‘ encoding=‘UTF-8‘?>\n";
        $xml .= "<root>\n";

        $xml .= self::_xml_encode($result);

        $xml .= "</root>\n";

        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);
 ?>

结果如下:

技术分享

APP接口返回数据的封装类

标签:

原文地址:http://www.cnblogs.com/jdhu/p/4189312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!