Method for Yii2 to output xml format data, yii2 to output xml format
Although xml processing in php is rarely used in actual development, it is inevitable to use it. When it is used, it is a little bit of trouble to sum up.
Let's take a look at how yii2 processes xml. It will be much simpler than you think.
Let's take the output data in xml format as an example.
Since it is output, web requests and responses are bound to be involved. If you are not familiar with it, you can first understand the HTTP protocol.
Yii2 supports the following return formats and can be customized.
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.
We are directed at XML.
First, let's look at a simple xml format data output.
public function actionTest () { \Yii::$app->response->format = \yii\web\Response::FORMAT_XML; return [ 'message' => 'hello world', 'code' => 100, ]; }
Here we specify the reponse response format FORMAT_XML, and then access the test method to see the xml data output on the page.
<response> <message>hello world</message> <code>100</code> </response>
The method mentioned above is a little troublesome. It is not so convenient to configure multiple items. Let's create a reponse object by ourselves.
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', // root node 'itemtag' => 'url', // unit],], 'data' => [// The data to be output ['loc '=> 'HTTP: // ******** ',]);}
For the sake of convenience, the above configuration is done. We can see that we have configured the response format and made some configuration separately, including configuring the root node rootTag, unit itemTag, and data type. Some people have noticed that, here we actually implement the xml format output of a site map. Yes, it's that simple.