解析非x-www-form-urlencoded类型的请求数据(json,xml) [ 2.0 版本 ]
组件配置添加:
'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格式适合微信公众号开发。
共 1 条评论
王甦冠 评论于 2016-05-28 21:35
……学习了……
发表评论
您需要登录后才可以评论。登录 | 立即注册