天天看點

php api資料響應類封裝

<?php

​​​​​​​​​​​​

class Response {

    public  function show($code, $message, $data = [], $type = 'json') { 

        if (!is_numeric($code) && !is_array($data)) {

            return false;

        }

        $result = [

            'code' => $code,

            'message' => $message,

            'data' => $data,

        ];

        $type = $_GET['format'] ? $_GET['format'] : $type;

        if ($type == 'json') {

            echo self::json($code, $message, $data);

            exit;

        } elseif ($type == 'xml') {

            echo self::xmlEncode($code, $message, $data);

        } elseif ($type == 'array') {

            var_dump($result);

        } else {

            //

    }

    // json api資料格式

    public static function json($code, $message, $data = []) {

        return json_encode($result);

        exit;

    // xml 格式

    public static function xmlEncode($code ,$message, $data = []) {

        if (!is_numeric($code)){

        header("Content-Type: text/xml");

        $xml = "<?xml version=1.0 encoding='UTF-8'?>\n";

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

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

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

        return $xml;

    public static function xmlToEncode($data) {

        $xml = '';

        foreach($data as $key=>$value) {

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

            $xml .= is_array($value) ? self::xmlToEncode($value) : $value;

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

}

?>