JsonOutput.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * Link : http://www.phpcorner.net
  4. * User : qingbing<780042175@qq.com>
  5. * Date : 2018-12-11
  6. * Version : 1.0
  7. */
  8. namespace Helper;
  9. defined('APP_CHARSET') or define('APP_CHARSET', 'utf-8');
  10. class JsonOutput
  11. {
  12. /**
  13. * 操作成功的JSON输出
  14. * @param array $data
  15. * @param string $message
  16. */
  17. public static function success($data = [], $message = 'success')
  18. {
  19. self::output($message, $data, 0);
  20. }
  21. /**
  22. * 操作失败的JSON输出
  23. * @param string $message
  24. * @param array $data
  25. * @param int $code
  26. */
  27. public static function failure($message = 'failure', $data = [], $code = -1)
  28. {
  29. self::output($message, $data, $code);
  30. }
  31. /**
  32. * 返回一个json字符串,然后终结应用
  33. * @param string $message
  34. * @param array $data
  35. * @param int $code
  36. */
  37. public static function output($message, $data = [], $code = 0)
  38. {
  39. header('Content-Type:text/html;Charset=' . APP_CHARSET);
  40. $output = [
  41. 'code' => $code,
  42. 'message' => $message,
  43. 'data' => $data,
  44. ];
  45. if (isset($_GET['e_callback']) && $_GET['e_callback']) {
  46. echo $_GET['e_callback'] . '(' . json_encode($output) . ')';
  47. } else {
  48. if (!headers_sent()) header('Content-type: application/json');
  49. echo json_encode($output);
  50. }
  51. }
  52. }