综合json、XML格式输出接口数据(代码)

代码:

接口对象:

<?php

class Response
{
    /**
     * 可选xml、json输出接口数据
     * @param int $code  返回状态码
     * @param string $msg   提示信息
     * @param array $data   数据数据
     * @param string $type  接口类型
     * @return string       返回字符串数据
     */
    public static function show( $code = 200,$msg = '',$data = array(),$type = 'json' )
    {
        if( !is_numeric($code) ){
            return '';
        }

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

        if( $type == 'json' ){
            self::json( $code,$msg,$data );
        } elseif( $type == 'xml' ){
            self::xml( $code , $msg ,$data );
        } elseif( $type = 'array' ){
            print_r($data);
        } else {
            //todo  可增加其他业务
        }
    }

    //json方式输出接口数据
    public static function json( $code = 200,$msg='',$data = array() )
    {
        if( !is_numeric($code) ){
            return '';
        }

        $data = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];

        echo json_encode($data);
    }

    //xml格式输出接口数据
    public static function xml($code,$msg,$data)
    {
        header("Content-type:text/xml;charset=utf-8");
        $xml = "<?xml version='1.0' encoding='UTF-8'?>";
        $xml .= "<root>\n";
        $xml .= "<code>{$code}</code>\n";
        $xml .= "<message>{$msg}</message>\n";
        $xml .= "<data>\n";
        $xml .= self::arrayToXml($data);
        $xml .= "</data>\n";
        $xml .= "</root>";

        echo $xml;
    }

    //数组转为xml格式
    public static function arrayToXml($data)
    {
        $xml = $attr = '';

        foreach( $data as $key => $val ){
            if( is_numeric($key) ){//xml节点不能为数字  故转化为<item id = '数字的形式'></item>
                $attr = " id='{$key}'";
                $key = "item";
            }

            $xml .= "<{$key}{$attr}>";

            $xml .= is_array($val) ? self::arrayToXml($val): $val;//多维数组时回调

            $xml .= "</{$key}>";
        }

        return $xml;
    }
}

应用举例

url地址为  http://url地址?format=xml

$data = array(
    'name' => 'alan',
    'sex'  => '男''age'  => 18
);

Response::show(200,'成功'$data);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值