Chinaunix首页 | 论坛 | 博客
  • 博客访问: 23153
  • 博文数量: 5
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 61
  • 用 户 组: 普通用户
  • 注册时间: 2016-08-03 11:15
文章分类
文章存档

2016年(5)

我的朋友
最近访客

分类: PHP

2016-08-03 14:56:08

1、封装接口文件   response.php

/*
*在另一个页面的调用
require_once('./responce.php');
Responce::show(200,'success',$data,'json')
*/

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 = '', $data = array(), $type = self::JSON) {
if(!is_numeric($code)) {
return '';
}

$type = isset($_GET['format']) ? $_GET['format'] : self::JSON;

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

if($type == 'json') {
self::json($code, $message, $data);
exit;
} elseif($type == 'array') {
var_dump($result);
} elseif($type == 'xml') {
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 = '', $data = array()) {

if(!is_numeric($code)) {
return '';
}

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

echo 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 '';
}

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

header("Content-Type:text/xml");
$xml = "\n";
$xml .= "\n";

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

$xml .= "
";
echo $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 .= "\n";
}
return $xml;
}

}


2、接口实现数据返回值 app.php

require_once('./response.php');
$data=array(
'username'=>'test',
'tel'=>'电话号码'
);

$type = isset($_GET['format']) ? $_GET['format'] : 'json';
Response::show(200,'success',$data,$type);

3、调用接口,获取数据


$cdapi = "";

$curl = curl_init();
curl_setopt ( $curl, CURLOPT_URL, $cdapi );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
if(!empty($data) && $post == 1){
curl_setopt ( $curl, CURLOPT_POST, $post );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
}
$res_id = json_decode(curl_exec ( $curl ),true);
curl_close ( $curl );

//多维数组转码
function array_iconv($in_charset,$out_charset,$arr)

        return eval('return '.mb_convert_encoding(var_export($arr,true).';',$out_charset,$in_charset));    
}

$res_id = array_iconv('utf-8','gbk',$res_id);
var_dump($res_id);

阅读(1586) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~