php中對xml的處理,雖然說實際開發中目前用的少了,但是難免會用到,用到的時候呢,總結起來還是稍稍有那么一丁點的麻煩。
我們來看看yii2中是怎么對xml進行處理的。會超乎你想象的簡單哦。
我們以輸出xml格式的數據為例。
既然是輸出,必然就涉及到web請求與響應了,不熟悉的可以先去了解下HTTP協議。
yii2中支持以下幾種返回格式,均可自定義配置。
HTML: implemented by yii/web/HtmlResponseFormatter.
XML: implemented by yii/web/XmlResponseFormatter.
JSON: implemented by yii/web/JsonResponseFormatter.
JSONP: implemented by yii/web/JsonResponseFormatter.
RAW: use this format if you want to send the response directly without applying any formatting.
我們就是沖著XML來的。
先來看一種簡單的輸出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格式輸出。是的,就是這么簡單。