This article mainly introduces the method of Yii2 outputting xml format data. It is of great reference value to make a small editor. I would like to share with you the script home platform for your reference on xml processing in php, although it is said that the actual development is currently used less, but it will inevitably be used, when it is used, it is still 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.
hello world
100
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.