标签:
1. JSON方式封装注意:该函数只能接收UTF-8编码的数据,如果传递其他类型的数据则会返回null。<? php$arr = array(‘id‘ => 1, ‘name‘ => ‘singwa‘);echo json_encode($arr);>
php字符串编码转换函数:iconv(); iconv(‘UTF-8‘,‘GBK‘,$data); 第一个参数为当前字符串格式,第二个参数为目标格式,第三个参数为待转换数据
class Response{/** 按json方式输出通信数据* @param integer $code 状态码* @param String $message 提示信息* @param array $data 数据* return String*/public static function json($code, $message = ‘‘, $data = array()){if(!is_numeric($code)){return ‘‘;}$result = array(‘code‘ => $code,‘message‘ => $message,‘data‘ => $data);echo json_encode($result);exit;}}
<?phprequire_once(./reponse.php);$arr = array(‘id‘ =>1,‘name‘ =>‘singwa‘);Response::json(200, ‘success‘, $arr);
public static function xml(){$xml = "<?xml version = ‘1.0‘ encoding = ‘UTF-8‘?>\n";$xml .="<root>\n";$xml .="<code>200</code>\n";$xml .="<message>数据返回成功</message>\n";$xml .="<data>\n";$xml .="<id>1</id>\n";$xml .="<name>singwa</name>\n";$xml .="</data>\n";$xml .="</root>\n";}
/** 按xml方式输出通信数据* @param integer $code 状态码* @param String $message 提示信息* @param array $data 数据* return String*/public static function xmlEncode($code, $message, $data = array()){if(!is_numeric($code)){return ‘‘;}$result = array(‘code‘ => $code,‘message‘ => $message,‘data‘ => $data);header("Content-Type:text/xml");$xml = "<?xml version = 1.0 encoding = ‘UTF-8‘?>";$xml .="<root>";$xml .=self::xmlToEncode($result); //解析数组,拼装成xml数据$xml .="</root>";}public static function xmlToEncode($data){$xml = $attr = "";foreach ($data as $key => $value){if(is_numeric($key)){$attr = "id = ‘{$key}‘";$key = "item";}$xml .="<{$key}>";$xml .= is_array($value) ? self::xmlToEncode($value):$value; // 判断$value的值是不是数组,是数据就进行递归处理$xml .="</{$key}>\n";}return $xml;}}
<?phprequire_once(./reponse.php);$arr = array(‘id‘ =>1,‘name‘ =>‘singwa‘);Response::xmlEncode(200, ‘success‘, $arr);
方法:show($code, $type, $message = ‘‘, $data = array());
/** 综合方式输出通信数据* @param integer $code 状态码* @param String $message 提示信息* @param array $data 数据* @param String $type 数据类型* return String*/public static function show($code, $type, $message = ‘‘, $data = array()){if(!is_numeric($code)){return ‘‘;}$result = array(‘code‘ => $code,‘message‘ => $message,‘data‘ => $data,);if($type == ‘json‘){self::json($code, $message, $data);exit;} else if($type == ‘array‘){var_dump($result);}elseif ($type == ‘xml‘) {self::xmlEncode($code, $message, $data);exit;} else {//TODO}}
标签:
原文地址:http://www.cnblogs.com/siguoyi/p/4445643.html