forked from eason-668/RESTful
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResponse.php
More file actions
77 lines (72 loc) · 2.17 KB
/
Response.php
File metadata and controls
77 lines (72 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
/**
* 输出类
*/
class Response
{
const HTTP_VERSION = "HTTP/1.1";
//返回结果
public static function sendResponse($data)
{
//获取数据
if ($data) {
$code = 200;
$message = 'OK';
} else {
$code = 404;
$data = array('error' => 'Not Found');
$message = 'Not Found';
}
//输出结果
header(self::HTTP_VERSION . " " . $code . " " . $message);
$content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : $_SERVER['HTTP_ACCEPT'];
if (strpos($content_type, 'application/json') !== false) {
header("Content-Type: application/json");
echo self::encodeJson($data);
} else if (strpos($content_type, 'application/xml') !== false) {
header("Content-Type: application/xml");
echo self::encodeXml($data);
} else {
header("Content-Type: text/html");
echo self::encodeHtml($data);
}
}
//json格式
private static function encodeJson($responseData)
{
return json_encode($responseData);
}
//xml格式
private static function encodeXml($responseData)
{
$xml = new SimpleXMLElement('<?xml version="1.0"?><rest></rest>');
foreach ($responseData as $key => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$xml->addChild($k, $v);
}
} else {
$xml->addChild($key, $value);
}
}
return $xml->asXML();
}
//html格式
private static function encodeHtml($responseData)
{
$html = "<table border='1'>";
foreach ($responseData as $key => $value) {
$html .= "<tr>";
if (is_array($value)) {
foreach ($value as $k => $v) {
$html .= "<td>" . $k . "</td><td>" . $v . "</td>";
}
} else {
$html .= "<td>" . $key . "</td><td>" . $value . "</td>";
}
$html .= "</tr>";
}
$html .= "</table>";
return $html;
}
}