综合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);

猜你喜欢

转载自blog.csdn.net/alan8865/article/details/80468022
今日推荐