Home > Backend Development > PHP Tutorial > Yii2 method to output xml format data

Yii2 method to output xml format data

WBOY
Release: 2016-07-29 08:51:38
Original
1099 people have browsed it

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, 
]; 
}
Copy after login

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> 
Copy after login

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://********', 
], 
], 
]); 
}
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template