Response.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace Heanup\Frame;
  3. class Response
  4. {
  5. const HTTP_VERSION = "HTTP/1.1";
  6. //返回结果
  7. public static function sendResponse($code, $data = [], $msg = 'OK')
  8. {
  9. //获取数据
  10. if ($code == 200) {
  11. $status = 200;
  12. $message = 'OK';
  13. } elseif ($code == 404) {
  14. $status = 404;
  15. $data = array('error' => 'Not Found');
  16. $message = 'Not Found';
  17. } elseif ($code == 405) {
  18. $status = 405;
  19. $data = array('error' => 'Method not allowed');
  20. $message = 'Method not allowed';
  21. } else {
  22. $status = 200;
  23. $message = $msg;
  24. }
  25. //输出结果
  26. header(self::HTTP_VERSION . " " . $status . " " . $message);
  27. $output = array(
  28. 'code' => (int)intval($code),
  29. 'message' => $message,
  30. );
  31. $content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : $_SERVER['HTTP_ACCEPT'];
  32. if (strpos($content_type, 'application/json') !== false) {
  33. if (is_array($data) && $data['page_config']) {
  34. $output = array_merge($output, $data);
  35. } else {
  36. $output['data'] = $data;
  37. }
  38. header("Content-Type: application/json");
  39. echo self::encodeJson($output);
  40. die();
  41. } else if (strpos($content_type, 'application/xml') !== false) {
  42. header("Content-Type: application/xml");
  43. echo self::encodeXml($output);
  44. die();
  45. } else {
  46. if (is_array($data) && $data['page_config']) {
  47. $output = array_merge($output, $data);
  48. } else {
  49. $output['data'] = $data;
  50. }
  51. header("Content-Type: application/json");
  52. echo self::encodeJson($output);
  53. die();
  54. }
  55. }
  56. //json格式
  57. private static function encodeJson($responseData)
  58. {
  59. $str = json_encode($responseData);
  60. return $str;
  61. }
  62. //xml格式
  63. private static function encodeXml($responseData)
  64. {
  65. $xml = new \SimpleXMLElement('<?xml version="1.0"?><rest></rest>');
  66. foreach ($responseData as $key => $value) {
  67. if (is_array($value)) {
  68. foreach ($value as $k => $v) {
  69. $xml->addChild($k, $v);
  70. }
  71. } else {
  72. $xml->addChild($key, $value);
  73. }
  74. }
  75. return $xml->asXML();
  76. }
  77. //html格式
  78. private static function encodeHtml($responseData)
  79. {
  80. $html = "<table border='1'>";
  81. foreach ($responseData as $key => $value) {
  82. $html .= "<tr>";
  83. if (is_array($value)) {
  84. foreach ($value as $k => $v) {
  85. $html .= "<td>" . $k . "</td><td>" . $v . "</td>";
  86. }
  87. } else {
  88. $html .= "<td>" . $key . "</td><td>" . $value . "</td>";
  89. }
  90. $html .= "</tr>";
  91. }
  92. $html .= "</table>";
  93. return $html;
  94. }
  95. }