Heim > php教程 > php手册 > Hauptteil

Yii2 输出xml格式数据的方法,yii2输出xml格式

WBOY
Freigeben: 2016-06-13 08:40:35
Original
927 Leute haben es durchsucht

Yii2 输出xml格式数据的方法,yii2输出xml格式

php中对xml的处理,虽然说实际开发中目前用的少了,但是难免会用到,用到的时候呢,总结起来还是稍稍有那么一丁点的麻烦。

我们来看看yii2中是怎么对xml进行处理的。会超乎你想象的简单哦。

我们以输出xml格式的数据为例。

既然是输出,必然就涉及到web请求与响应了,不熟悉的可以先去了解下HTTP协议。

yii2中支持以下几种返回格式,均可自定义配置。

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.

我们就是冲着XML来的。

先来看一种简单的输出xml格式数据

public function actionTest () { 
\Yii::$app->response->format = \yii\web\Response::FORMAT_XML; 
return [ 
'message' => 'hello world', 
'code' => 100, 
]; 
}
Nach dem Login kopieren

这里我们指定了reponse响应格式 FORMAT_XML,然后访问这个test方法就可以看到页面上输出了xml类型的数据

<response> 
<message>hello world</message> 
<code>100</code> 
</response> 
Nach dem Login kopieren

上面提到的方式未免有点麻烦,麻烦在配置多项的时候就不是那么方便了,我们来自己创建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://********', 
], 
], 
]); 
}
Nach dem Login kopieren

为了方便接下来的说明,上面一并做了配置,可以看到我们配置了响应的格式format,单独做了些配置,包括配置根节点rootTag,单元itemTag以及数据类型。有同学注意到了,这里其实我们很简单的就实现了一个站点地图的xml格式输出。是的,就是这么简单。

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!