yii2解析非x-www-form-urlencoded类型的请求数据(json,xml)

组件配置添加:

'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
'application/xml' => 'common\components\XmlParser',
'text/xml' => 'common\components\XmlParser'
]
],
'response' => [
'formatters' => [
\yii\web\Response::FORMAT_XML => [
'class' => 'yii\web\XmlResponseFormatter',
'rootTag' => 'xml'
]
]
]

common\components\XmlParser

<?php

namespace common\components;

use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\RequestParserInterface; class XmlParser implements RequestParserInterface
{
public $asArray = true; public $throwException = true; /**
* Parses a HTTP request body.
* @param string $rawBody the raw HTTP request body.
* @param string $contentType the content type specified for the request body.
* @return array parameters parsed from the request body
* @throws BadRequestHttpException if the body contains invalid json and [[throwException]] is `true`.
*/
public function parse($rawBody, $contentType)
{
try {
$parameters = simplexml_load_string($rawBody, 'SimpleXMLElement', LIBXML_NOCDATA);
$parameters = $this->asArray ? (array) $parameters : $parameters;
return $parameters === null ? [] : $parameters;
} catch (InvalidParamException $e) {
if ($this->throwException) {
throw new BadRequestHttpException('Invalid XML data in request body: ' . $e->getMessage());
}
return [];
}
}
}

然后就可以在控制器里直接取$params = Yii::$app->bodyParams

xml格式适合微信公众号开发。

上一篇:ARMV8 datasheet学习笔记4:AArch64系统级体系结构之存储模型


下一篇:iOS模型以及使用