国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

PHP生成json和xml類型接口數據格式

2024-05-04 23:35:19
字體:
來源:轉載
供稿:網友

在做數據接口時,我們通常要獲取第三方數據接口或者給第三方提供數據接口,而這些數據格式通常是以XML或者JSON格式傳輸,本文將介紹如何使用PHP生成XML格式數據供第三方調用以及如何獲取第三方提供的XML數據。

php生成接口通信數據

 

 
  1. /** 
  2. * 生成接口數據格式 
  3. */ 
  4. class Response{ 
  5. /** 
  6. * [show 按綜合方式輸出數據] 
  7. * @param [int] $code [狀態碼] 
  8. * @param [string] $message [提示信息] 
  9. * @param array $data [數據] 
  10. * @param [string] $type [類型] 
  11. * @return [string] [返回值] 
  12. */ 
  13. public static function show($code$message$data = array(),$type = ''){ 
  14. if(!is_numeric($code)){ 
  15. return ''
  16. $result = array
  17. 'code' => $code
  18. 'message' => $message
  19. 'data' => $data 
  20. ); 
  21. if($type == 'json'){ 
  22. return self::json($code$message$data); 
  23. }elseif($type == 'xml'){ 
  24. return self::xml($code$message$data); 
  25. }else
  26. //TODO 
  27. /** 
  28. * [json 按json方式輸出數據] 
  29. * @param [int] $code [狀態碼] 
  30. * @param [string] $message [提示信息] 
  31. * @param [array] $data [數據] 
  32. * @return [string] [返回值] 
  33. */ 
  34. public static function json($code$message$data = array()){ 
  35. if(!is_numeric($code)){ 
  36. return ''
  37. $result = array
  38. 'code' => $code
  39. 'message' => $message
  40. 'data' => $data 
  41. ); 
  42. $result = json_encode($result); 
  43. return $result
  44.  
  45. /** 
  46. * [xml 按xml格式生成數據] 
  47. * @param [int] $code [狀態碼] 
  48. * @param [string] $message [提示信息] 
  49. * @param array $data [數據] 
  50. * @return [string] [返回值] 
  51. */ 
  52. public static function xml($code$message$data = array()){ 
  53. if(!is_numeric($code)){ 
  54. return ''
  55. $result = array
  56. 'code' => $code
  57. 'message' => $message
  58. 'data' => $data 
  59. ); 
  60. header("Content-Type:text/xml"); 
  61. $xml = "<?xml version='1.0' encoding='UTF-8'?>/n"
  62. $xml .= "<root>/n"
  63. $xml .= self::xmlToEncode($data); 
  64. $xml .= "</root>"
  65. return $xml
  66.  
  67. public static function xmlToEncode($data){ 
  68. $xml = ''
  69. foreach($data as $key => $value){ 
  70. if(is_numeric($key)){ 
  71. $attr = "id='{$key}'"
  72. $key = "item"
  73. $xml .= "<{$key} {$attr}>/n"
  74. $xml .= is_array($value) ? self::xmlToEncode($value) : "{$value}/n"
  75. $xml .= "</{$key}>/n"
  76. return $xml
  77.  
  78. //測試 
  79. $grade = array("score" => array(70, 95, 70.0, 60, "70"), "name" => array("Zhang San""Li Si""Wang Wu""Zhao Liu""TianQi")); 
  80. $response = new Response(); 
  81. $result = $response :: show(200,'success',$grade,'json'); 
  82. print_r($result); 

以上所述就是本文的全部內容了,希望大家能夠喜歡。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 内黄县| 双江| 林芝县| 五峰| 明水县| 峨山| 蚌埠市| 吉木萨尔县| 林周县| 扬中市| 南昌县| 南江县| 双桥区| 纳雍县| 雷州市| 万全县| 梨树县| 丽江市| 海门市| 潼南县| 托里县| 云和县| 泰来县| 兴文县| 聂拉木县| 高碑店市| 平和县| 淮滨县| 吴江市| 津市市| 万宁市| 浏阳市| 福州市| 通化县| 蒙自县| 南阳市| 泸定县| 楚雄市| 徐闻县| 崇仁县| 清河县|