<?php
class Response
{
//默认为json格式
const JSON = 'json';
/**
*选择json或xml方式输出通信数据
*@param int $code 状态码
*@param string $message 提示信息
*@param array $data 数据
*@param string $type 数据类型
*return string
*/
public static function show($code, $message = '', $data = [], $type = self::JSON)
{
if (!is_numeric($code)) {
return '';
}
#从客户端直接接收数据 format格式
$type = isset($_GET['format']) ? $_GET['format'] : self::JSON;
//返回的数据(未转换)
$result = [
'code' => $code,
'message' => $message,
'data' => $data
];
if ($type == 'json') {
//生成json数据
self::json($code, $message, $data);
} elseif ($type == 'xml') {
//生成xml数据
self::xml_encode($code, $message, $data);
} elseif ($type == 'array') {
//调试输出
var_dump($result);
} else {
//后续添加
exit;
}
}
/**
*按json方式输出通信数据
*@param int $code 状态码
*@param string $message 提示信息
*@param array $data 数据
*return string
*/
public static function json($code, $message = '', $data = [])
{
if (!is_numeric($code)) {
return '';
}
$result = [
'code' => $code,
'message' => $message,
'data' => $data
];
echo json_encode($result);
exit;
}
/*
#php生成xml数据
public static function xml()
{
#显示为xml格式
header("Content-Type:text/xml; charset=UTF-8");
$xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xml .= "<root>\n";
$xml .= "<code>200</code>\n";
$xml .= "<message>数据返回成功</message>\n";
$xml .= "<data>\n";
$xml .= "<id>1</id>\n";
$xml .= "<name>小白</name>\n";
$xml .= "</data>\n";
$xml .= "</root>";
echo $xml;
exit;
}
*/
/**
*按xml方式输出通信数据
*@param int $code 状态码
*@param string $message 提示信息
*@param array $data 数据
*return string
*/
public static function xml_encode($code, $message = '', $data = [])
{
if (!is_numeric($code)) {
return '';
}
$result = [
'code' => $code,
'message' => $message,
'data' => $data,
];
//指定页面显示的信息为xml格式
header("Content-Type:text/xml");
$xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xml .= "<root>\n";
$xml .= self::xml_2_encode($result);
$xml .= "</root>";
echo $xml;
exit;
}
/**
*解析¥$data数组,拼装成xml数据
*@param array $data 数据
*return string
*/
public static function xml_2_encode($data)
{
$xml = '';
$attr = '';
foreach($data as $key=>$value) {
if (is_numeric($key)) {
$attr = " id='{$key}'";
$key = "item";
}
$xml .= "<{$key}{$attr}>";
//把数组递归显示出来
//xml节点不能为数字'<0>节点为0错误<0>'
$xml .= is_array($value)? self::xml_2_encode($value): $value;
$xml .= "</{$key}>\n";
}
return $xml;
}
}
/*
#测试数据
$arr = [
'id' => 1,
'name' => '小白',
3,4,5,
'type' => [7,8,9=>[10,11]]
];
Response::json(200, 'successs', $arr);
Response::xml_encode(200, 'successs', $arr);
*/
<?php
require('./response.php');
$arr = [
'id' => 1,
'name' => '小白',
3,4,5,
'type' => [7,8,9=>[10,11]]
];
Response::show(200,'数据返回成功',$arr);
/*
http://127.0.0.1/PHP/demo/test.php?format=xml
http://127.0.0.1/PHP/demo/test.php?format=json
*/
--如有冲突,请通知本人删除