Created
July 10, 2017 08:56
-
-
Save why168/4d39508d8c4e29feb2adae551b4a96a8 to your computer and use it in GitHub Desktop.
PHP封装数据
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: edwin | |
* Date: 2017/7/1 | |
* Time: 01:29 | |
*/ | |
class Response | |
{ | |
const JSON = 'json'; | |
/** | |
* @param $code 状态码 | |
* @param string $message 提示信息 | |
* @param array $data 数据 | |
* @param string $type 数据类型 | |
* @return string | |
*/ | |
public static function show($code, $message = '', $data = array(), $type = self::JSON) | |
{ | |
if (!is_numeric($code)) { | |
return ''; | |
} | |
$type = isset($_GET['format']) ? $_GET['format'] : $type; | |
$result = array( | |
'code' => $code, | |
'message' => $message, | |
'data' => $data | |
); | |
if ($type == 'json') { | |
self::json($code, $message, $data); | |
exit; | |
} else if ($type == 'xml') { | |
self::xml($code, $message, $data); | |
} else if ($type == 'array') { | |
var_dump($result); | |
} else { | |
//TODO | |
} | |
} | |
/** | |
* JSON方式输出通信数据 | |
* @param $code 状态码 | |
* @param string $message 提示信息 | |
* @param array $data 数据 | |
* @return string | |
*/ | |
public static function json($code, $message = '', $data = array()) | |
{ | |
if (!is_numeric($code)) { | |
return ''; | |
} | |
$result = array( | |
'code' => $code, | |
'message' => $message, | |
'data' => $data | |
); | |
header("Content-Type: charset=utf8; application/json;"); | |
echo json_encode($result, JSON_UNESCAPED_UNICODE); | |
exit; | |
} | |
/** | |
* XML方式输出通信数据 | |
* @param $code 状态码 | |
* @param string $message 提示信息 | |
* @param array $data 数据 | |
* @return string | |
*/ | |
public static function xml($code, $message = '', $data = array()) | |
{ | |
if (!is_numeric($code)) { | |
return ''; | |
} | |
$result = array( | |
'code' => $code, | |
'message' => $message, | |
'data' => $data | |
); | |
header("Content-Type: charset=utf8; text/xml;"); | |
$xml = "<?xml version='1.0' encoding='UTF-8'?>\n"; | |
$xml .= "<root>\n"; | |
$xml .= self::xmlTo($result); | |
$xml .= "</root>"; | |
echo $xml; | |
exit; | |
} | |
private static function xmlTo($data) | |
{ | |
$xml = $attr = ""; | |
foreach ($data as $key => $value) { | |
if (is_numeric($key)) { | |
$attr = " id='{$key}'"; | |
$key = "item"; | |
} | |
$xml .= "<{$key}{$attr}>"; | |
$xml .= is_array($value) ? self::xmlTo($value) : $value; | |
$xml .= "</{$key}>\n"; | |
} | |
return $xml; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment