做者:白狼 出處:http://www.manks.top/yii2_xml_response.html.html本文版權歸做者,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。php
php中對xml的處理,雖說實際開發中目前用的少了,可是不免會用到,用到的時候呢,總結起來仍是稍稍有那麼一丁點的麻煩。html
咱們來看看yii2中是怎麼對xml進行處理的。會超乎你想象的簡單哦。web
咱們以輸出xml格式的數據爲例。json
既然是輸出,必然就涉及到web請求與響應了,不熟悉的能夠先去了解下HTTP協議。yii2
yii2中支持如下幾種返回格式,都可自定義配置。app
HTML: implemented by yii\web\HtmlResponseFormatter.yii
XML: implemented by yii\web\XmlResponseFormatter.this
JSON: implemented by yii\web\JsonResponseFormatter.url
JSONP: implemented by yii\web\JsonResponseFormatter.spa
RAW: use this format if you want to send the response directly without applying any formatting.
先來看一種簡單的輸出xml格式數據
public function actionTest () { \Yii::$app->response->format = \yii\web\Response::FORMAT_XML; return [ 'message' => 'hello world', 'code' => 100, ]; }
這裏咱們指定了reponse響應格式 FORMAT_XML,而後訪問這個test方法就能夠看到頁面上輸出了xml類型的數據
<response> <message>hello world</message> <code>100</code> </response>
上面提到的方式未免有點麻煩,麻煩在配置多項的時候就不是那麼方便了,咱們來本身建立reponse對象試一試
public function actionTest () { 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' => 'http://********', ], ], ]); }
爲了方便接下來的說明,上面一併作了配置,能夠看到咱們配置了響應的格式format,單獨作了些配置,包括配置根節點rootTag,單元itemTag以及數據類型。有同窗注意到了,這裏其實咱們很簡單的就實現了一個站點地圖的xml格式輸出。是的,就是這麼簡單。