<?PHPclassresponse_json_xml{ Public Static functionShow$code,$message="",$data=Array(),$type){ if(Is_null($code)){ return‘‘; } $data=Array( ' Code ' =$code, ' message ' =$message, ' data ' =$data ); if($type= = "JSON") { self:: JSON ($code,$message,$data); die; }Else if($type= = "Array"){ Var_dump($data); die; }ElseIf($type= = "xml") { self:: Xml_encoding ($code,$message,$data); die; }Else{ //coding .... } } /** * Output communication as JSON * @param integet $code Status code * @param string $message message * @param array $data data * return string
*/ Public Static functionJson$code,$message,$data=Array()){ if(Is_null($code)){ return‘‘; } $result=Array( ' Code ' =$code, ' message ' =$message, ' data ' =$data ); EchoJson_encode ($result); die; } /** * Output communication as XML * @param integet $code Status code * @param string $message message * @param array $data data * return string */ Public Static functionXml_encoding ($code,$message,$data=Array()){ if(Is_null($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::xml_array ($result); $xml. = "</root>\n"; Echo $xml; } Public Static functionXml_array ($result){ $xml=$attr=""; foreach($result as $key=$value) { if(Is_numeric($key)){ $attr= "Id= ' {$key}‘"; $key= "Item"; } $xml. = "<{$key}{$attr}>\n "; $xml.=Is_array($value)? Self::xml_array ($value):$value; $xml. = "</{$key}>\n "; } return $xml; }} $data=Array( ' id ' =>1, ' name ' = ' hgj123 ', ); $data 1=Array(1,2,3,11,122); $type=isset($_get[' type '])?$_get[' type ']: ' JSON '; Response_json_xml:: Show (200, ' success ',$data,$type);
Json,xml Hybrid Package Communication