转化字符编码iconv('UTF-8','GBK',$data);
标准格式:
code 状态代码
message 提示信息
data 数据
简单json数据封装:
public static function json($code,$message='',$data=array()){
if(!is_numeric($code) || !is_array($data)){
return '';
}
$result = array(
'code' => $code,
'message' => $message,
'data' => $data,
);
echo json_encode($result);
exit;
}
简单xml数据封装:
两种实现方式:
组装字符串
DomDocument
XMLWriter
SimpleXML
为了让页面显示XML结构,可以采用header("Content-Type:text/xml");
xml通信接口封装:
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' ?>\n";
$xml .= "<root>\n";
$xml .= self::xmltoEncode($result);
$xml .= "</root>";
echo $xml;
}
public static function xmltoEncode($data){
$xml = $attr = "";
foreach ($data as $key => $value) {
if(is_numeric($key)){
$attr = "id='{$key}'";
$key = "item ";
}
$xml .= "<{$key}{$attr}>";
$xml .= is_array($value)?self::xmltoEncode($value):$value;
$xml .= "</{$key}>\n";
}
return $xml;
}