做者:白狼 出处: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格式输出。是的,就是这么简单。