雖然 JSON 為主流,但對接舊系統、生成 Sitemap、RSS、API 規範要求時,XML 仍不可或缺。Yii2 內建 XmlResponseFormatter,支援一鍵切換響應格式、自定義根節點、元素標籤,極大簡化 XML 輸出開發。
public function actionTest() {
Yii::$app->response->format = yii\web\Response::FORMAT_XML;
return [
'message' => 'hello world',
'code' => 100,
];
}
// 輸出:
// <response><message>hello world</message><code>100</code></response>
public function actionSitemap() {
return Yii::createObject([
'class' => 'yii\web\Response',
'format' => yii\web\Response::FORMAT_XML,
'formatters' => [
yii\web\Response::FORMAT_XML => [
'class' => 'yii\web\XmlResponseFormatter',
'rootTag' => 'urlset', // 根節點
'itemTag' => 'url', // 陣列元素標籤
],
],
'data' => [
['loc' => 'https://example.com/page1'],
['loc' => 'https://example.com/page2'],
['loc' => 'https://example.com/page3'],
],
]);
}
// 輸出符合 sitemap.org 規範:
// <urlset><url><loc>https://example.com/page1</loc></url>...</urlset>
| 格式常數 | Formatter 類別 | 說明 |
|---|---|---|
| FORMAT_HTML | HtmlResponseFormatter | 預設,渲染 View |
| FORMAT_XML | XmlResponseFormatter | 陣列轉 XML,支援 rootTag/itemTag |
| FORMAT_JSON | JsonResponseFormatter | JSON 編碼 |
| FORMAT_JSONP | JsonResponseFormatter | JSONP 回調 |
| FORMAT_RAW | 無 | 直接輸出字串,不做格式化 |
public function actionRss() {
$posts = Post::find()->orderBy(['created_at' => SORT_DESC])->limit(20)->all();
$items = [];
foreach ($posts as $p) {
$items[] = [
'title' => $p->title,
'link' => Url::to(['post/view', 'id' => $p->id], true),
'description' => $p->summary,
'pubDate' => date('r', $p->created_at),
'guid' => Url::to(['post/view', 'id' => $p->id], true),
];
}
return Yii::createObject([
'class' => 'yii\web\Response',
'format' => yii\web\Response::FORMAT_XML,
'formatters' => [
yii\web\Response::FORMAT_XML => [
'class' => 'yii\web\XmlResponseFormatter',
'rootTag' => 'rss',
'itemTag' => 'item',
],
],
'data' => [
'@version' => '2.0',
'channel' => [
'title' => '我的部落格',
'link' => Url::home(true),
'description' => '最新文章',
'item' => $items,
],
],
]);
}
<0>),建議統一使用關聯陣列。memory_limit,可考慮分批輸出或使用 XMLWriter 流式寫入。Yii2 的 XmlResponseFormatter 配合 Yii::createObject 建立響應物件,能以極少代碼實現高度客製化的 XML 輸出,完美滿足 Sitemap、RSS、SOAP、舊系統對接等場景需求。