版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。http://blog.youkuaiyun.com/mayongzhan - 马永占,myz,mayongzhan
xmlrpc是webservice
大家都说比soap要简单...我怎么没看出来,代码都写的很多
当然也要有server 和 client 端
类
<?php
/**
* @name xmlrpcTest.php
* @date Fri Jan 25 12:11:54 CST 2008
* @copyright 马永占(MyZ)
* @author 马永占(MyZ)
* @link http://blog.youkuaiyun.com/mayongzhan/
*/
/**
* Math methods
*/
class Math
{
/**
* Return the sum of all values in an array
*
* @param array $values An array of values to sum
* @return int
*/
public static function add($method, $params)
{
return array_sum($params[0]);
}
}
/**
* Return the product of some values
*
* @param string $method The XML-RPC method name called
* @param array $params Array of parameters from the request
* @return int
*/
function product($method, $params)
{
return $params;
}
?>
server
<?php
/**
* @name xmlrpcTestServer.php
* @date Fri Jan 25 12:11:54 CST 2008
* @copyright 马永占(MyZ)
* @author 马永占(MyZ)
* @link http://blog.youkuaiyun.com/mayongzhan/
*/
require('xmlrpcTest.php');
//产生一个XML-RPC的服务器端
$xmlrpc_server = xmlrpc_server_create();
//注册一个服务器端调用的方法rpc_server,实际指向的是rpc_server_func函数
xmlrpc_server_register_method($xmlrpc_server, 'math.add', array('Math', 'add'));
xmlrpc_server_register_method($xmlrpc_server, 'product', 'product');
//接受客户端POST过来的XML数据
$request = $HTTP_RAW_POST_DATA;
//$request = file_get_contents('php://input');
//执行调用客户端的XML请求后获取执行结果
$xmlrpc_response = xmlrpc_server_call_method($xmlrpc_server, $request, null);
//把函数处理后的结果XML进行输出
header('Content-Type: text/xml');
echo $xmlrpc_response;
//销毁XML-RPC服务器端资源
xmlrpc_server_destroy($xmlrpc_server);
?>
client
<?php
/**
* @name xmlrpcTestClient.php
* @date Fri Jan 25 12:11:47 CST 2008
* @copyright 马永占(MyZ)
* @author 马永占(MyZ)
* @link http://blog.youkuaiyun.com/mayongzhan/
*/
try
{
$request = xmlrpc_encode_request('math.add',array(array(1,2)),array('encoding' => 'UTF-8'));
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml",
'content' => $request
)));
$file = file_get_contents('http://127.0.0.1/test/xmlrpcTestServer.php', false, $context);
if(!file) {
throw new Exception('错误:得不到webservice的response');
}
$response = xmlrpc_decode($file);
if (is_array($response) && xmlrpc_is_fault($response))
{
throw new Exception($response['faultString'],
$response['faultCode']);
}
echo $response;
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>