<?php class Response{ public static function show($code,$message = '',$data = array(),$type = 'json'){ if(!is_numeric($code)){ return ''; } $type=isset($_GET['format'])?$_GET['format']:'json'; $result=array( 'code' => $code, 'message' => $message, 'data' => $data, ); if($type=='json'){ self::json($code,$message,$data); exit; }elseif($type=='array'){ echo "<pre>"; var_dump($result); echo "</pre>"; }elseif($type=='xml'){ self::xmlEncode($code,$message,$data); exit; }else{ //TODD } } public static function json($code, $message = '', $data = array()) { if(!is_numeric($code)) { return ''; } $result = array( 'code' => $code, 'message' => $message, 'data' => $data ); $result=json_encode($result); $result=preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $result); echo $result; exit; } 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='gb2312'?>"; $xml .= "<root>"; $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; } }
php返回xml,json,array
最新推荐文章于 2021-03-31 09:33:00 发布