首页 >php教程 >PHP源码 >输出数据跟前端实现通信

输出数据跟前端实现通信

PHP中文网
PHP中文网原创
2016-05-26 08:21:12904浏览

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);

?>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn