<?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);
exit;
} elseif ($type == 'array') {
var_dump($result);
} else {
//
}
}
// json api数据格式
public static function json($code, $message, $data = []) {
if (!is_numeric($code) && !is_array($data)) {
return false;
}
$result = [
'code' => $code,
'message' => $message,
'data' => $data,
];
return json_encode($result);
exit;
}
// xml 格式
public static function xmlEncode($code ,$message, $data = []) {
if (!is_numeric($code)){
return false;
}
$result = [
'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>\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;
}
return $xml;
}
}
?>