Controller使用 Transform 编码 JSON 和 xml 数据

This commit is contained in:
麦当苗儿
2013-04-19 17:16:43 +08:00
parent 93cd95640b
commit 6f512306e8
2 changed files with 24 additions and 6 deletions

View File

@@ -85,16 +85,16 @@ class Controller {
case 'JSON':
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:application/json; charset=utf-8');
exit(json_encode($data));
exit(Think\Transform::jsonEncode($data));
case 'XML':
// 返回xml格式数据
header('Content-Type:text/xml; charset=utf-8');
exit(xml_encode($data));
exit(Think\Transform::xmlEncode($data));
case 'JSONP':
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:application/javascript; charset=utf-8');
$handler = isset($_GET[C('var_jsonp_handler')]) ? $_GET[C('var_jsonp_handler')] : C('default_jsonp_handler');
exit($handler . '(' . json_encode($data) . ');');
exit($handler . '(' . Think\Transform::jsonEncode($data) . ');');
case 'SCRIPT':
// 返回可执行的js脚本
header('Content-Type:application/javascript; charset=utf-8');

View File

@@ -13,9 +13,14 @@ namespace Think;
// 内容解析类
class Transform {
static private $handler = [];
/**
* 初始化解析驱动
* @static
* @access private
* @param string $type 驱动类型
*/
static private function init($type){
if(!isset(self::$handler[$type])) {
$class = '\\Think\\Transform\\Driver\\' . ucwords($type);
@@ -23,13 +28,26 @@ class Transform {
}
}
// 编码内容
/**
* 编码内容
* @static
* @access public
* @param mixed $content 要编码的数据
* @param string $type 数据类型
* @return string 编码后的数据
*/
static public function encode($content, $type){
self::init($type);
return self::$handler[$type]->encode($content);
}
// 解码内容
/**
* 解码数据
* @param string $content 要解码的数据
* @param string $type 数据类型
* @param boolean $assoc 是否返回数组
* @return mixed 解码后的数据
*/
static public function decode($content, $type, $assoc = true){
self::init($type);
return self::$handler[$type]->decode($content, $assoc);