Reference Video http://www.imooc.com/learn/163
<?PHP/** * The app returns data class * 1. Accept multidimensional, missing key-name Array, * 2. The return data format can be determined by the input format parameter * Example: Response::show ($, ' success ', $data);*/classresponse{ConstJSON = ' json '; /** * Output communication data in JSON format*/ Public Static functionJson$result) { EchoJson_encode ($result); } /** * Encode data part of XML*/ Private Static function_xml_encode ($data) { $xml= ""; foreach($data as $key=$value) { //if the key name is a number, change to <item id= "0" ></item> format $attr= ' '; if(Is_numeric($key)) { $attr= "Id= ' {$key}‘"; $key= "Item"; } //if the key value is an array, recursively calls itself $xml. = "<{$key}{$attr}> "; $xml.=Is_array($value) ? "\ n". Self::_xml_encode ($value) :$value; $xml. = "</{$key}>\n "; } return $xml; } /** * Output communication data in XML format*/ Public Static functionxml$result) { Header("Content-type:text/xml"); $xml= "<?xml version= ' 1.0 ' encoding= ' UTF-8 '? >\n"; $xml. = "<root>\n"; $xml. = Self::_xml_encode ($result); $xml. = "</root>\n"; Echo $xml; } /** * Output communication data in input format*/ Public Static functionShow$code,$message= "",$data=Array(),$type= Self::JSON) { if( !Is_numeric($code)) { die(' JSON input parameter requires number '); } //If there is a requested format type $type=isset($_get[' Format ']) ?$_get[' Format ']:$type; $result=Array( ' Code ' =$code, ' message ' =$message, ' data ' =$data, ); if($type= = ' json ') { self:: JSON ($result); } ElseIf($type= = ' xml ') { self:: XML ($result); } ElseIf($type= = ' array ') { Echo' <pre> '; Print_r($result); Echo' </pre> '; } Exit; }}//a multidimensional, missing array of key names, which can be determined by the input format parameter to return data formats$data=Array( ' id ' = 1, ' name ' = ' haha ', ' addr 'Array(1,2,3=>Array(' hh ')),); Response:: Show ($, ' success ',$data); ?>
The results are as follows:
Package class for app interface return data