Write yourself a class that generates Json/xml format data that can be used for API data transfer:
1<?PHP2 classresponse{3 /**4 * Generate the specified data format5 * @param intval $code Status Code6 * @param string $message status Description7 * @param array $data data8 * @param string $type The data format required to return9 * @return string $data dataTen */ One Public Static functionDataType ($code,$message,$data= ",$type= ' xml '){ A - if(In_array($type,Array(' JSON ', ' xml ', ' array '))) { - if($type= = ' json ') { the $data= Self::json ($code,$message,$data); -}ElseIf($type= = ' xml ') { - $data= Self::xml ($code,$message,$data); -}ElseIf($type= = ' array ') { + Var_dump(Self::d ata ($code,$message,$data)); -}Else{ + Exit; A } at } - } - - /** - * Generate data formats in JSON format - * @param intval $code in * @param string $message - * @param array $data to * @return String + */ - Public Static functionJson$code,$message,$data){ the $data= self::d ata ($code,$message,$data); * EchoJson_encode ($data); $ Exit;Panax Notoginseng } - /** the * Generate data formats in XML format + * @param intval $code A * @param string $message the * @param array $data + * @return String - */ $ Public Static functionxml$code,$message,$data){ $ $data= self::d ata ($code,$message,$data); - Header("Content-type:text/xml"); - $xml= ' <?xml version= ' 1.0 ' encoding= ' UTF-8 '?> '; the $xml. = ' <note> '; - $xml. = Self::xmltoencode ($data);Wuyi $xml. = ' </note> '; the Echo $xml; - Exit; Wu } - /** About * Create an XML node $ * @param array $data - * @return String $xml - */ - Public Static functionXmltoencode ($data){ A $xml= ' '; + foreach($data as $k=$v) { the $attr= ' '; - if(Is_numeric($k)) { $ $attr= "Id= ' {$k}‘"; the $k= ' Item '; the } the $xml. = "<{$k}{$attr}> "; the $xml.=Is_array($v)? Self::xmltoencode ($v):$v; - $xml. = "</$k> "; in } the return $xml; the } About the /** the * Create data formats in array format the * @param intval $code + * @param string $message - * @param array $data the * @return Array $dataBayi */ the Public Static functionData$code,$message,$data){ the if(!Is_numeric($code)) { - return‘‘; - } the $data=Array( the' Code ' =$code, the' Message ' =$message, the' Data ' =$data - ); the return $data; the } the 94 } the?>
JSON, XML----data format generation class