1<?PHP2 classreponse{3 //Private $result = Array (' Code ' =null, ' message ' =null, ' data ' =>null);4 /**5 * @desc return JSON format6 * @param int $code7 * @param string $message8 * @param array $data9 * Return stringTen */ One Public Static functionJson$code,$message=NULL,$data=Array()){ A if(!Is_numeric($code)){ - return false; - } the $result=Array( -' Code ' =$code, -' Message ' =$message, -' Data ' =$data + ); - returnJson_encode ($result); + Exit; A } at - /** - * @desc return XML Format Data - * @parma int $code Status Code - * @param string $message hint - * @param array $data data in * Return string - */ to Public Static functionxml$code,$message= ",$data=Array()){ + if(!Is_numeric($code)){ - return false; the } * $result=Array( $' Code ' =$code,Panax Notoginseng' Message ' =$message, -' Data ' =$data the ); + $xml= ' '; A the $xml. = "<?xml version= ' 1.0 ' encoding= ' UTF-8 '? >\n"; + $xml. = "<root>\n"; - $xml. = Self::xmlencode ($result); $ $xml. = "</root>"; $ Header("Content-type:text/xml"); - Echo $xml; - the } - Wuyi Public Static functionXmlencode ($result){ the $xml=$attr= ' '; - foreach($result as $key=$val){ Wu if(Is_numeric($key)){ - $attr= "Id= ' {$key}‘"; About $key= "item{$key}"; $ } - $xml. = "<{$key} {$attr}> "; - - $xml.=Is_array($val) ? Self::xmlencode ($val) :$val; A + $xml. = "</{$key}>\n "; the } - $ return $xml; the the } the the } - in $data=Array( the' ID ' =>1, the' Age ' =>20, About' Username ' = ' tim ', the' Others ' =Array(a), the ); theReponse::xml, ' success ',$data); +Reponse::json, ' success ',$data);
PHP returns JSON and XML classes