Home > php教程 > PHP源码 > body text

输出数据跟前端实现通信

PHP中文网
Release: 2016-05-26 08:21:12
Original
886 people have browsed it

PHP面向对象编程

<?php

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

 $type = isset($_GET[&#39;format&#39;]) ? $_GET[&#39;format&#39;] : (isset($_POST[&#39;format&#39;]) ? $_POST[&#39;format&#39;] : self::JSON);

$result = array(
&#39;code&#39; => $code,
&#39;message&#39; => $message,
&#39;data&#39; => $data,
);

if($type == &#39;json&#39;) {
self::json($code, $message, $data);
exit;
} elseif($type == &#39;array&#39;) {
var_dump($result);
} elseif($type == &#39;xml&#39;) {
self::xmlEncode($code, $message, $data);
exit;
} else {
// TODO
}
}
/**
* 按json方式输出通信数据
* @param integer $code 状态码
* @param string $message 提示信息
* @param array $data 数据
* return string
*/
public static function json($code, $message = &#39;&#39;, $data = array()) {

if(!is_numeric($code)) {
return &#39;&#39;;
}

$result = array(
&#39;code&#39; => $code,
&#39;message&#39; => $message,
&#39;data&#39; => $data
);

 header("Content-Type: application/json; charset=utf-8");

echo urldecode(json_encode($result));
exit;
}

/**
* 按xml方式输出通信数据
* @param integer $code 状态码
* @param string $message 提示信息
* @param array $data 数据
* return string
*/
public static function xmlEncode($code, $message, $data = array()) {
if(!is_numeric($code)) {
return &#39;&#39;;
}

$result = array(
&#39;code&#39; => $code,
&#39;message&#39; => $message,
&#39;data&#39; => $data,
);

header("Content-Type:text/xml");
$xml ="<?xml version=&#39;1.0&#39; encoding=&#39;UTF-8&#39;?>n";
$xml .="<root>n";

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

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

 public static function xmlToEncode($data) {

 $xml ="";
 foreach($data as $key => $value) {
 $attr ="";
 if(is_numeric($key)) {
 $attr ="id=&#39;{$key}&#39;";
 $key ="item";
}
 $xml .="<{$key}{$attr}>";
 $xml .= is_array($value) ? self::xmlToEncode($value) : $value;
 $xml .="</{$key}>n";
}
 return $xml;
}

};

$da = array("SUCCESS");
echo Response::show(200, urlencode(&#39;登陆成功&#39;),$da);

?>
Copy after login
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template