一、啥是XML-RPC
XML-RPC可以理解为简化版的soap,对数据的包装相对简洁。
二、配置
打开php.ini扩展,打开以下扩展,配置完重启Apache。
三、构建服务
1.新建rpc-server.php rpc服务端
<?php
function hello(){
return 'hhahaha';
}
//创建RPC服务器
$server=xmlrpc_server_create();
//把用户写的函数注册到RPC服务器中
xmlrpc_server_register_method($server,'hello','hello');
//收取POST请求(内容是XML格式)
$request=$HTTP_RAW_POST_DATA;
//调用相关的方法
$response=xmlrpc_server_call_method($server,$request,null);
//输出
header('content-type:text/xml');
echo $response;
xml_server_destroy($server);
?>
2.新建rpc-client.php
封装自己的rpc-client请求类
class rpcclient{
protected $url;
public function __construct($url){
$this->url=$url;
}
protected function __query($request){
$context=stream_context_create(
array(
'http'=>array(
'method'=>'POST',
'header'=>'Content-Type:text/xml',
'content'=>$request
)
)
);
$xml=file_get_contents($this->url,false,$context);
//var_dump($xml);
return xmlrpc_decode($xml);
}
//遇到未定义的方法时,此方法未被调用
public function __call($method,$args){
$request=xmlrpc_encode_request($method,$args);
return $this->__query($request);
}
}
2.手写HTTP协议,看返回结果。
POST /webservice/rpc-server.php HTTP/1.1
Host:localhost
Content-type:textdomain/xml
content-length:260
<?xml version="1.0" encoding="iso-8859-1"?>
<methodCall>
<methodName>hello</methodName>
<params>
<param>
<value>
<string>zhong</string>
</value>
</param>
<param>
<value>
<string>guo</string>
</value>
</param>
</params>
</methodCall>
返回结果:
3.服务端增加代码
<?php
function hello(){
return 'hhahaha';
}
/*
*注意,rpc服务器在调用函数时,传的参数是这样的
array(0=>'函数名',1=>array(实参1,实参2,...实参N),2=>NULL);
* */
function sum($method,$args,$extra){
return array_sum($args);
}
//创建RPC服务器
$server=xmlrpc_server_create();
//把用户写的函数注册到RPC服务器中
xmlrpc_server_register_method($server,'hello','hello');
xmlrpc_server_register_method($server,'sum','sum');
//收取POST请求(内容是XML格式)
$request=$HTTP_RAW_POST_DATA;
//调用相关的方法
$response=xmlrpc_server_call_method($server,$request,null);
//输出
header('Content-Type:text/xml');
echo $response;
xmlrpc_server_destroy($server);
?>
4.客户端调用服务端
$client=new rpcclient('http://localhost/webservice/rpc-server.php');
echo $client->hello('aa','bb');
print_r($client->sum(4,5,6));