首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Yii2 輸出 XML 格式資料:Response Formatter 配置與自定義根節點實戰

     編輯:PHP 綜合知識

前言

雖然 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>

進階:自定義 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_HTMLHtmlResponseFormatter預設,渲染 View
FORMAT_XMLXmlResponseFormatter陣列轉 XML,支援 rootTag/itemTag
FORMAT_JSONJsonResponseFormatterJSON 編碼
FORMAT_JSONPJsonResponseFormatterJSONP 回調
FORMAT_RAW無直接輸出字串,不做格式化

實戰:生成 RSS 2.0 Feed

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,
            ],
        ],
    ]);
}

注意事項

  • XML 不支援陣列鍵為數字的情況(會轉為 <0>),建議統一使用關聯陣列。
  • 特殊字元(& < >)會自動轉義,無需手動處理。
  • 大量資料時注意 memory_limit,可考慮分批輸出或使用 XMLWriter 流式寫入。

總結

Yii2 的 XmlResponseFormatter 配合 Yii::createObject 建立響應物件,能以極少代碼實現高度客製化的 XML 輸出,完美滿足 Sitemap、RSS、SOAP、舊系統對接等場景需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved