Standard format of communication data:
codestatus code (200, 400, etc.);
messageprompt information (login failure, data return success, etc.);
data Return data;
1. The json method encapsulates the communication interface
method: json_encode($value);
Note: This function can only accept utf-8 encoded data; if passed For data in other formats, this function will return null;
class Response
{
/**
* 按json方式输出通信数据
* @param int $code 状态码
* @param 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,
);
echo json_encode($result);
exit;
}
}
?>
2. Encapsulate the communication interface in xml method
Method: PHP generates xml data;
How to first use PHP There are two ways to generate xml data:
1. Assemble into xml string;
2. Use system classes (DomDocument, XMLWriter, SimpleXML);
class Response
{
/**
* 按xml方式输出通信数据
* @param int $code 状态码
* @param string $message 提示信息
* @param array $data 数据
* @return void
*/
public static function xmlEncode($code,$message='',$data=array())
{
$r = '';
if(!is_numeric($code)) $r = '';
$result = array(
'code'=>$code,
'message'=>$message,
'data'=>$data,
);
header("Content-Type:text/xml");
$xml = "\n";
$xml .= "\n";
$xml .= self::xmlToEncode($result);
$xml .= "";
$r = $xml;
echo $r;
}
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;
}
}
?>
Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.
The above introduces the PHP_APP communication interface - the method of encapsulating the communication interface, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.