yidashi 2016-05-27 18:20:02 3130次浏览 2条评论 0 3 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格式适合微信公众号开发。

觉得很赞
亿速云
您需要登录后才可以评论。登录 | 立即注册