PHP_APP communication interface—method of encapsulating communication interface

WBOY
Release: 2016-07-30 13:31:48
Original
1192 people have browsed it

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!