為前後端分離提供統一數據格式,支援按需輸出 JSON 或 XML。核心方法 show() 根據 $type 參數分發。
<?php
class Response {
/** 綜合輸出入口 */
public static function show($code, $message, $data = [], $type = '') {
if (!is_numeric($code)) return '';
$result = ['code' => $code, 'message' => $message, 'data' => $data];
if ($type === 'json') return self::json($code, $message, $data);
if ($type === 'xml') return self::xml($code, $message, $data);
return ''; // TODO: 其他格式
}
/** JSON 輸出 */
public static function json($code, $message, $data = []) {
if (!is_numeric($code)) return '';
return json_encode(['code' => $code, 'message' => $message, 'data' => $data]);
}
/** XML 輸出 */
public static function xml($code, $message, $data = []) {
if (!is_numeric($code)) return '';
header("Content-Type:text/xml");
$xml = "<?xml version='1.0' encoding='UTF-8'?>\n<root>\n";
$xml .= self::xmlToEncode($data);
$xml .= "</root>";
return $xml;
}
/** 遞歸生成 XML 節點 */
private static function xmlToEncode($data) {
$xml = '';
foreach ($data as $key => $value) {
$attr = is_numeric($key) ? "id='{$key}'" : '';
$tag = is_numeric($key) ? 'item' : $key;
$xml .= "<{$tag} {$attr}>\n";
$xml .= is_array($value) ? self::xmlToEncode($value) : "{$value}\n";
$xml .= "</{$tag}>\n";
}
return $xml;
}
}
?>
<?php
$grade = [
"score" => [70, 95, 70.0, 60, "70"],
"name" => ["Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "TianQi"]
];
$response = new Response();
$result = $response::show(200, 'success', $grade, 'json');
print_r($result);
// 輸出: {"code":200,"message":"success","data":{"score":[70,95,70,60,"70"],"name":["Zhang San","Li Si","Wang Wu","Zhao Liu","TianQi"]}}
?>
若傳 'xml' 則輸出對應 XML 結構。此類易於擴展支持更多格式。