PHP对接APP的接口类,可返回json数据,xml数据

<?php
/*
 * APP数据处理类
 * 作  者:永乐开发
 * 日  期:2017.7.31
 * 邮  箱:web@isu5.cn
 * 博  客:http://www.isu5.cn  http://it.alipea.com
 */


class Response{
	
	
	/**
	* 综合方法 默认json方法调用
	* @param integer $code 状态码
	* @param string $msg 提示信息
	* @param string $data 数据
	* return string
	*
	*/
	public static function show($code,$msg,$data=[],$type=''){
		if (!is_numeric($code)) {
			return '';
		}

	
		
		$result = array(
			'code' => $code,
			'msg' => $msg,
			'data' => $data
			);
                $type = $_GET['format'] ? $_GET['format'] : '';
		if ($type=='json') {
			//json形式
			self::returnJson($code,$msg,$result);
			exit;
		}elseif ($type=='array') {
			//数组形式
			var_dump($result);
		}elseif ($type=='xml') {
			self::xmlEncode($code,$msg,$result);
			exit;
		}else{
			//TODO
		}
	}
	
	/**
	* 按json数据传输
	* @param integer $code 状态码
	* @param string $msg 提示信息
	* @param string $data 数据
	* return string
	*
	*/
	public static function returnJson($code,$msg,$data=[],$type='json'){
		if (!is_numeric($code)) {
			return '';
		}
		$result = array(
			'code' => $code,
			'msg' => $msg,
			'data' => $data
			);
		echo json_encode($result);
		exit;
	}
	
	/**
	* 按xml数据传输
	* @param integer $code 状态码
	* @param string $msg 提示信息
	* @param string $data 数据
	* return string
	*
	*/
	
	public static function xmlEncode($code,$msg,$data=[]){
		if (!is_numeric($code)) {
			return '';
		}
		$result = array(
			'code' => $code,
			'msg' => $msg,
			'data' => $data
			);
		header("Content-Type:text/xml");
		$xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
		$xml .="<root>\n"; //根节点

		$xml .=self::xmlToEncode($result);

		$xml .="</root>";

		echo $xml;

	}

	public static function xmlToEncode($data){
		$xml = $attr = "";
		foreach ($data as $key => $value) {
		
			//如果key值为数字
			if (is_numeric($key)) {
				$attr = " id='{$key}'";
				$key = "item";
			}
			
			$xml .="<{$key}{$attr}>";
			
			//递归直到字符串为止
			$xml .= is_array($value)?self::xmlToEncode($value):$value;

			$xml .="</{$key}>\n";

		}
		return $xml;
	}

	
}


调用方法:

Response::show(200,'提示信息',$data);


访问地址:

http://localhost/index.php?format=json   返回json数据

http://localhost/index.php?format=xml   返回xml数据



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱酥网络

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值