Xml processing in PHP is rarely used in actual development, but it is inevitably used. When used, in summary, it is still a little troublesome.
Let’s take a look at how xml is processed in yii2. It will be easier than you think.
We take outputting data in xml format as an example.
Since it is output, it must involve web requests and responses. If you are not familiar with it, you can first understand the HTTP protocol.
yii2 supports the following return formats, all of which can be customized.
HTML: implemented by yiiwebHtmlResponseFormatter.
XML: implemented by yiiwebXmlResponseFormatter.
JSON: implemented by yiiwebJsonResponseFormatter.
We are here for XML.
Let’s first look at a simple output of xml format data
public function actionTest () { \Yii::$app->response->format = \yii\web\Response::FORMAT_XML; return [ 'message' => 'hello world', 'code' => 100, ]; }
Here we specify the response format FORMAT_XML, and then access this test method to see that xml type data is output on the page
<response> <message>hello world</message> <code>100</code> </response>
The method mentioned above is a bit troublesome. It is not so convenient when configuring multiple items. Let’s try to create the response object 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', //根节点 'itemTag' => 'url', //单元 ], ], 'data' => [ //要输出的数据 [ 'loc' => 'http://********', ], ], ]); }
In order to facilitate the following explanation, we will do the above together. After configuring, you can see that we have configured the response format and made some separate configurations, including configuring the root node rootTag, unit itemTag and data type. Some students have noticed that here we have actually implemented a site map output in xml format very simply. Yes, it's that simple.
The above introduces the method of Yii2 outputting xml format data, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.