zoukankan      html  css  js  c++  java
  • php封装一个接口类

    1. <?php
      Class Response
      {
      //返回数据
      public static function show($code,$message='',$data='',$type = 'json',$callback='')
      {
      if($type=='json')
      {
      echo self::jsonEncode($code,$message,$data);
      }elseif($type == 'xml')
      {
      echo self::xmlEncode($code,$message,$data);
      }elseif($type == 'jsonp')
      {
      echo $callback.'('.self::jsonEncode($code,$message,$data).')';
      }

      }

      //json接口
      public static function jsonEncode($code,$message='',$data='')
      {
      if(!is_numeric($code))
      {
      return '';
      }

      $result = array(
      'code' => $code,
      'message' => $message,
      'data' => $data,
      );
      header("Content-type:text/json;chaset=utf-8");
      return json_encode($result);
      }
      //xml接口
      public static function xmlEncode($code,$message,$data=array())
      {
      if(!is_numeric($code))
      {
      return '';
      }

      $result = array(
      'code' => $code,
      'message' => $message,
      'data' => $data,
      );

      header("Content-type:text/xml;chaset=utf-8");
      $xml = "<?xml version='1.0' encoding='utf-8' ?> ";
      $xml .= "<root> ";
      $xml .= self::xmlToEncode($result);
      $xml .= "</root> ";

      return $xml;

      }

      //xml内容循环
      public static function xmlToEncode($data)
      {
      if(empty($data))
      {
      return '';
      }
      $xml = $attr = '';
      foreach ($data as $key => $value)
      {
      if(is_numeric($key))
      {
      $attr = "id='{$key}'";
      $key = "item";
      }
      $xml .= "<{$key} {$attr}>";
      $xml .= is_array($value) ? self::xmlToEncode($value) : $value ;
      $xml .= "</{$key}> ";
      }

      return $xml;
      }
      }


      //二维数据
      $type = isset($_GET['type'])? $_GET['type'] : 'json';

      $callback = isset($_GET['callback'])? $_GET['callback'] : '';


      $arr = array(
      'id'=>1,
      'name'=>'jia',
      'type'=>array(1,2,3)
      );

      Response::show(200,'数据返回成功',$arr,$type,$callback);
  • 相关阅读:
    免费的编程中文书籍索引
    整理书签博客和文章
    【De8ug玩docker】-Docker常用命令操作
    Linux中的那些英文缩写和她的含义们
    Docker和DevOps是找工作必备技能
    【De8ug玩docker】-命令行只显示-bash-4.1#
    应该知道的Linux技巧
    阿里云服务器linux(centos)常用命令
    jQuery运维开发之第十七天
    js+dom开发第十六天
  • 原文地址:https://www.cnblogs.com/Pxhphp/p/6485773.html
Copyright © 2011-2022 走看看