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

结果如下:

image

posted @ 2014-12-27 22:36  yo胡yo  阅读(895)  评论(0编辑  收藏  举报