The code is very concise, function is also very simple and practical, here is not much nonsense, directly to the code:
Copy Code code as follows:
<?php
Class reponse{
Private $result = Array (' Code ' =null, ' message ' =null, ' data ' =>null);
/**
* @desc return JSON format
* @param int $code
* @param string $message
* @param array $data
* Return string
*/
public static function JSON ($code, $message = null, $data = Array ()) {
if (!is_numeric ($code)) {
return false;
}
$result = Array (
' Code ' => $code,
' Message ' => $message,
' Data ' => $data
);
Return Json_encode ($result);
Exit
}
/**
* @desc return XML Format data
* @parma int $code Status code
* @param string $message hints
* @param array $data data
* Return string
*/
public static function XML ($code, $message = ', $data = Array ()) {
if (!is_numeric ($code)) {
return false;
}
$result = Array (
' Code ' => $code,
' Message ' => $message,
' Data ' => $data
);
$xml = ';
$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;
}
public static function Xmlencode ($result) {
$xml = $attr = ';
foreach ($result as $key => $val) {
if (Is_numeric ($key)) {
$attr = "id= ' {$key} '";
$key = "item{$key}";
}
$xml. = "<{$key} {$attr}>";
$xml. = Is_array ($val)? Self::xmlencode ($val): $val;
$xml. = "</{$key}>\n";
}
return $xml;
}
}
$data = Array (
' ID ' =>1,
' Age ' =>20,
' username ' => ' Tim ',
' Others ' =>array (1,2,3),
);
Reponse::xml (' success ', $data);
Reponse::json (' success ', $data);
Small partners can be used directly, using the method at the bottom of the code:)