PHP开发APP接口 记录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a519395243/article/details/78696332
用于 把数据返给APP接口使用 ,返回 方式有 xml,json,array

class Response {
	/**
	* 综合方式输出数据
	* @param integer $code 状态码
	* @param string $message 提示信息
	* @param array $data 数据
	* @param string $type 数据类型
	* return string
	*/
	public static function show($code, $message = '', $data = array(), $type ='json') {
		if(!is_numeric($code)) {
			return '';
		}

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

		if($type == 'json') {
			echo self::json($code, $message, $data);
			exit;
		} elseif($type == 'array') {
			var_dump($result);
		} elseif($type == 'xml') {
			echo self::xml($code, $message, $data);
			exit;
		} else {
			//没有类型
			return false;
		}
	}

	//将数据转化为json
	public static function json($code, $message = '', $data = array()) {
		
		if(!is_numeric($code)) {
			return '';
		}

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

	    return json_encode($result);
	}

	//将数据转化为xml
	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 = "<?xml version='1.0' encoding='UTF-8'?>\n";
		$xml .= "<root>\n";

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

		$xml .= "</root>";
		return $xml;
	}

	public static function xmlToEncode($data) {
		$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}>\n";
		}
		return $xml;
	}

}


实例: 

<?php
	
	include_once('response.php');

	$data = [
		'name'=>'D',
		'age'=>'18'
	];
	//url后面加个 type 参数,用get获取,方便让app工程师得到需要的数据格式
	$type = empty($_GET['type'])?'json':$_GET['type'];
	Response::show('200','success',$data,$type);


猜你喜欢

转载自blog.csdn.net/a519395243/article/details/78696332