API 開發中,統一的回應結構能大幅提升前後端協作效率。本文提供一個可直接用於專案的 Response 類別,支援 JSON 與 XML 兩種格式輸出,結構包含狀態碼、訊息與資料三欄位。
<?php
class Response
{
/**
* 回傳 JSON 格式
* @param int $code 狀態碼
* @param string $message 訊息
* @param array $data 資料陣列
* @return string JSON 字串
*/
public static function json($code, $message = null, $data = [])
{
if (!is_numeric($code)) {
return false;
}
$result = [
'code' => $code,
'message' => $message,
'data' => $data
];
return json_encode($result, JSON_UNESCAPED_UNICODE);
}
/**
* 回傳 XML 格式
* @param int $code 狀態碼
* @param string $message 訊息
* @param array $data 資料陣列
* @return void 直接輸出 XML
*/
public static function xml($code, $message = '', $data = [])
{
if (!is_numeric($code)) {
return false;
}
$result = [
'code' => $code,
'message' => $message,
'data' => $data
];
$xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xml .= "<root>\n";
$xml .= self::xmlEncode($result);
$xml .= "</root>";
header("Content-Type: text/xml; charset=UTF-8");
echo $xml;
}
/**
* 遞迴將陣列轉為 XML 節點
* @param array $data
* @return string
*/
private static function xmlEncode($data)
{
$xml = '';
foreach ($data as $key => $val) {
$attr = '';
if (is_numeric($key)) {
$attr = " id='{$key}'";
$key = "item{$key}";
}
$xml .= "<{$key}{$attr}>";
$xml .= is_array($val) ? self::xmlEncode($val) : htmlspecialchars($val, ENT_QUOTES, 'UTF-8');
$xml .= "</{$key}>\n";
}
return $xml;
}
}
<?php
require_once 'Response.php';
$data = [
'id' => 1,
'age' => 20,
'username' => 'tim',
'others' => [1, 2, 3],
];
// JSON 輸出
echo Response::json(200, 'success', $data);
// 輸出: {"code":200,"message":"success","data":{"id":1,"age":20,"username":"tim","others":[1,2,3]}}
// XML 輸出
Response::xml(200, 'success', $data);
/* 輸出:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<code>200</code>
<message>success</message>
<data>
<id>1</id>
<age>20</age>
<username>tim</username>
<others>
<item0 id='0'>1</item0>
<item1 id='1'>2</item1>
<item2 id='2'>3</item2>
</others>
</data>
</root>
*/
?>
Response::json() 呼叫。code、message、data 三欄位固定,前端解析更簡單。xmlEncode 中使用 htmlspecialchars 防止 XML 注入。item0, item1... 並保留原索引為 id 屬性。JSON_UNESCAPED_UNICODE,XML 宣告 UTF-8 編碼。http_response_code($code)。這個輕量類別適合中小型專案快速導入,大型專案建議使用框架內建的 Resource/Transformer 機制。