沐风待雨 2017-02-18 14:37:32 14186次浏览 4条回复 12 4 0

网上看到的这里摘录留存下

Yii2 接收 POST 数据是使用 Yii::$app->request->post(); ,但是如果发送过来的数据格式是 json 或 xml 的时候,通过这个方法就无法获取到数据了, Yii2 这么强大的组件型框架肯定想到了这一点。

对于 json 的解析 Yii2 已经写好了 [[JsonResponseFormatter]] ,在配置文件里面配置一下即可使用。

file app/config/main.php

'components' =>[
	'request' => [
		'parsers' => [
			'application/json' => 'yii\web\JsonParser',
			'text/json' => 'yii\web\JsonParser',
		],
	],
],

配置好之后访问提交过来的数据就太简单啦

# json raw data
{"username": "bob"}

# access data
$post_data = Yii::$app->request->post();
echo $post_data["username"];

# or
echo Yii::$app->request->post("username");

通过框架找到了 JsonParser 所在的目录发现了一个接口 [[RequestParserInterface]] ,并在 JsonParser 的同级目录下未找到 XmlParser 的类,基于 Yii2 组件框架,于是自己来写一个 Parser 用来解析 xml 数据,只需要实现接口提供的方法即可 [[RequestParserInterface::parse()]] ,这里最主要的是将 xml 的数据转换成数组的一个过程,通过 Google 找了很多 "xml to array",大部分的解析结果我并不满意,要么是功能不完整,要么就是结果不准确,但最终我还是找到了比较完善的 "xml to array" 的类 xml2array ,创建一个类,实现 xml2array 的功能。

file: common/tools/Xml2Array.php 目录不存在的话需要创建

<?php

namespace common\tools;
class Xml2Array
{
	// 把那个网站上的方法复制过来,并在方法前面加上 public static 把方法名换成 go
	// 注释部分建议也复制过来,这对以后追溯代码的出处很有用。
	// 替换之后的基本格式为:
	public static function go($contents, $get_attributes=1, $priority = 'tag')
	{
		... ...
	}
}

file common/components/XmlRequestParser.php

namespace common\components;
use yii\web\RequestParserInterface;
use common\tools\Xml2Array;
class XmlRequestParser implements  RequestParserInterface
{
	public function parse($rawBody, $contentType)
	{
		$content = Xml2Array::go($rawBody);
		return array_pop($content);
	}
}
# file app/config/main.php
'components' =>[
	'request' => [
		'parsers' => [
			'text/xml' => 'common\components\XmlRequestParser',
			'application/xml' => 'common\components\XmlRequestParser',
			'application/json' => 'yii\web\JsonParser',
			'text/json' => 'yii\web\JsonParser',
		],
	],
],

经过上面的三步之后,就可以直接访问提交过来的 xml 数据了。

# raw data
<xml><username><![CDATA[bob]]></username></xml>

# access data
Yii::$app->request->post('username');

这样不管别人传过来的数据是 html、json、xml 格式都可以非常方便的获取了,在和各种接口打交道的时候用上这个可以方便太多了。

觉得很赞
您需要登录后才可以回复。登录 | 立即注册