• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP生成json和xml类型接口数据格式_php实例

php 搞代码 3年前 (2022-01-25) 22次浏览 已收录 0个评论

php生成接口通信数据

/** * 生成接口数据格式 */class Response{  /**   * [show 按综合方式输出数据]   * @param [int] $code    [状态码]   * @param [string] $message [提示信息]   * @param array $data  [数据]   * @param [string] $type [类型]   * @return [string]    [返回值]   */  public static function show($code, $message, $data = array(),$type = ''){    if(!is_numeric($code)){      return '';    }    $result = array(      'code' => $code,      'message' => $message,      'data' => $data    );    if($type == 'json'){      return self::json($code, $message, $data);    }elseif($type == 'xml'){      return self::xml($code, $message, $data);    }else{      //TODO    }  }  /**   * [json 按json方式输出数据]   * @param [int] $code    [状态码]   * @pa<span style="color:transparent">/本文来源gaodai#ma#com搞*!代#%^码网%</span><sub>搞代gaodaima码</sub>ram [string] $message [提示信息]   * @param [array] $data  [数据]   * @return [string]     [返回值]   */  public static function json($code, $message, $data = array()){    if(!is_numeric($code)){      return '';    }    $result = array(      'code' => $code,      'message' => $message,      'data' => $data    );    $result = json_encode($result);    return $result;  }   /**   * [xml 按xml格式生成数据]   * @param [int] $code    [状态码]   * @param [string] $message [提示信息]   * @param array $data   [数据]   * @return [string]     [返回值]   */  public static function xml($code, $message, $data = array()){    if(!is_numeric($code)){      return '';    }    $result = array(      'code' => $code,      'message' => $message,      'data' => $data    );    header("Content-Type:text/xml");    $xml = "\n";    $xml .= "\n";    $xml .= self::xmlToEncode($data);    $xml .= "";    return $xml;  }   public static function xmlToEncode($data){    $xml = '';    foreach($data as $key => $value){      if(is_numeric($key)){        $attr = "id='{$key}'";        $key = "item";      }      $xml .= "\n";      $xml .= is_array($value) ? self::xmlToEncode($value) : "{$value}\n";      $xml .= "\n";    }    return $xml;  }} //测试$grade = array("score" => array(70, 95, 70.0, 60, "70"), "name" => array("Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "TianQi"));$response = new Response();$result = $response :: show(200,'success',$grade,'json');print_r($result);

以上所述就是本文的全部内容了,希望大家能够喜欢。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP生成json和xml类型接口数据格式_php实例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址