PHP开发APP接口(二):封装通信接口方法

1)JSON方式封装通信接口

a)PHP生成JSON数据

$data = "输出json数据";

// 字符串的编码转换 iconv(in_charset, out_charset, str)
// $newData = iconv('UTF-8', 'GBK', $data);

// 这个函数只能接受utf-8的编码的数据,如果传递其他格式的数据该函数会返回null
echo json_encode($data);

b)通信数据标准格式

返回格式需要包括:
// code     状态码(200,400等)
// message  提示信息(邮箱格式不正确;数据返回成功等)
// data     返回数据

封装接口方法路径:app/response.php

class Response {
    /**
     * [json 按json方式输出通信数据]
     * @Author   ZJC
     * @DateTime 2017-02-14T11:58:07+0800
     * @param    [integer]                $code    [状态码]
     * @param    string                   $message [提示信息]
     * @param    array                    $data    [数据]
     * @return   [sting]                           [返回json数据]
     */
    public static function json($code, $message = '', $data = array()) {
        if(!is_numeric($code)) {    //判断是否数字
            return '';
        }
        $result = array(
            'code' => $code,
            'message' => $message,
            'data' => $data
        );
        echo json_encode($result);
        exit;
    }
}

封装路径:app/test.php

require_once('./response.php');
$arr = array(
    'id' => 1,
    'name' => 'singwa'
);
Response::json(200, '数据返回成功', $arr);

2)PHP生成XML数据

a)PHP生成XML数据

组装字符串
使用系统类(DomDocument、XMLWriter、SimpleXML)

b)XML方式封装接口数据方法

class Response {
    public static function xml() {
        // 记住要加header,发送原生的 HTTP 头,才能在网页上查看到标准的XML格式
        header('Content-Type:text/xml');
        $xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
        $xml .= "<root>\n";
        $xml .= "<code>200</code>\n";
        $xml .= "<message>数据返回成功</message>\n";
        $xml .= "<data>\n";
        $xml .= "<id>1</id>\n";
        $xml .= "<name>singwa</name>\n";
        $xml .= "</data>\n";
        $xml .= "</root>";

        echo $xml;
    }
}
Response::xml();

3)XML方式封装通信接口

XML方式封装接口数据方法

class Response {
    /**
     * [xmlEncode 按xml方式输出通信数据]
     * @Author   ZJC
     * @DateTime 2017-02-14T11:58:07+0800
     * @param    [integer]                $code    [状态码]
     * @param    string                   $message [提示信息]
     * @param    array                    $data    [数据]
     * @return   [sting]                           [返回json数据]
     */
    public static function xmlEncode($code, $message, $data = array()) {
        if (!is_numeric($code)) {
            return '';
        }
        $result = array(
            'code' => $code,
            'message' => $message,
            'data' => $data
        );

        header("Content-Type:text/xml");
        $xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
        $xml .= "<root>\n"; 
        $xml .= self::xmlToEncode($result);
        $xml .= "</root>";
        echo $xml;
    }
    // 把数组转换成XML节点
    public static function xmlToEncode($data) {
        $xml = $attr = "";
        foreach ($data as $key => $value) {
            // 健值为数字,转换成<item id="{$key}"></item>
            if(is_numeric($key)) {
                $attr = " id='{$key}'";
                $key = "item";
            }
            $xml .= "<{$key}{$attr}>";
            $xml .= is_array($value) ? self::xmlToEncode($value) : $value;
            $xml .="</{$key}>\n";
        }
        return $xml;
    }
}

//实例
$data = array(
    'id' => 1,
    'name' => 'singwa',
    'type' => array(4,5,6),     //数组里没写健值,因此健值默认为0,1,2的情况,需要转换成<item id="0"></item>
    'test' => array(1,45,67=>array(123, 'test')),
);
Response::xmlEncode(200, 'success', $data);

4)综合方式封装通信数据方法

封装方法:show($code, $message, $data=array(), $type='json')
class Response {
    // 常量为默认返回数据类型
    const JSON = 'json';
    /**
     * [show 综合通信方法]
     * @Author   ZJC
     * @DateTime 2017-02-14T16:57:48+0800
     * @param    [type]                   $code    [状态码]
     * @param    string                   $message [提示信息]
     * @param    array                    $data    [数据]
     * @param    [type]                   $type    [数据类型]
     * @return   [type]                            [返回json数据]
     */
    public static function show($code, $message = '', $data = array(), $type = self::JSON) {
        if(!is_numeric($code)) {
            return '';
        }

        $type = isset($_GET['format']) ? $_GET['format'] : self::JSON;

        $result = array(
            'code' => $code,
            'message' => $message,
            'data' => $data
        );

        if($type == 'json') {
            self::json($code, $message, $data);
            exit;
        } elseif($type == 'array') {    // 调试查看传递过来的数据
            var_dump($result);
        } elseif($type == 'xml') {
            self::xmlEncode($code, $message, $data);
            exit;
        } else {
            // TODO
        }
    }
    // 下面代码为json和xml的封装方法,此处省略
}

调用路径:app/test.php

require_once('./response.php');
$data = array(
    'id' => 1,
    'name' => 'singwa',
    'type' => array(4,5,6),
    'test' => array(1,45,67=>array(123, 'test')),
);
Response::show(200, 'success', $data, 'array');
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值