PHP中使用XML-RPC构造Web Service简单入门 - php语言 -

PHP中使用XML-RPC构造Web Service简单入门

时间:2013-04-02 16:53:23   来源:   评论:加载中...   点击:加载中...
[ Web Service介绍 ]  Web Service就是为了异构系统的通信而产生...

服务器端构造好了,那么再构造我们的RPC客户端。客户端大致通过Socket访问XML-RPC服务器端的80端口,然后把需要调用的RPC接口封装到XML里,通过POST请求提交给RPC服务器端,最后获取服务器端返回结果。

代码如下:rpc_client.php

<?php
/**
 * 函数:提供给客户端进行连接XML-RPC服务器端的函数
 * 参数:
 * $host  需要连接的主机
 * $port  连接主机的端口
 * $rpc_server XML-RPC服务器端文件
 * $request  封装的XML请求信息
 * 返回:连接成功成功返回由服务器端返回的XML信息,失败返回false
 */
function rpc_client_call($host, $port, $rpc_server, $request) {

   file://打开指定的服务器端
   $fp = fsockopen($host, $port);

   file://构造需要进行通信的XML-RPC服务器端的查询POST请求信息
   $query = "POST $rpc_server HTTP/1.0nUser_Agent: XML-RPC ClientnHost: ".$host."nContent-Type: text/xmlnContent-Length: ".strlen($request)."nn".$request."n";

   file://把构造好的HTTP协议发送给服务器,失败返回false
   if (!fputs($fp, $query, strlen($query)))
   {
       $errstr = "Write error";
       return false;
   }
  
   //获取从服务器端返回的所有信息,包括HTTP头和XML信息
   $contents = '';
   while (!feof($fp))
   {
       $contents .= fgets($fp);
   }

   //关闭连接资源后返回获取的内容
   fclose($fp);
   return $contents;
}

//构造连接RPC服务器端的信息
$host  = 'localhost';
$port  = 80;
$rpc_server = '/~heiyeluren/rpc_server.php';

//把需要发送的XML请求进行编码成XML,需要调用的方法是rpc_server,参数是get
$request = xmlrpc_encode_request('rpc_server', 'get');

//调用rpc_client_call函数把所有请求发送给XML-RPC服务器端后获取信息
$response = rpc_client_call($host, $port, $rpc_server, $request);

//分析从服务器端返回的XML,去掉HTTP头信息,并且把XML转为PHP能识别的字符串
$split = '<?xml version="1.0" encoding="iso-8859-1"?>';
$xml =  explode($split, $response);
$xml = $split . array_pop($xml);
$response = xmlrpc_decode($xml);

//输出从RPC服务器端获取的信息
print_r($response);

?>



相关热词搜索:

 
上一篇:PHP Shell的编写(改进版)
下一篇:PHP开发中接收复选框信息的方法
收藏 将此文推荐给朋友
分享到: