欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php xml-rpc远程调用

程序员文章站 2022-12-26 15:50:31
复制代码 代码如下:
复制代码 代码如下:

<?php
/*
从网上找来的xml-rpc库,对于开发小型的外部通讯接口很有用
*/

function & xml_serialize($data, $level = 0, $prior_key = null){
#assumes a hash, keys are the variable names
$xml_serialized_string = "";
while(list($key, $value) = each($data)){
$inline = false;
$numeric_array = false;
$attributes = "";
#echo "my current key is '$key', called with prior key '$prior_key'<br>";
if(!strstr($key, " attr")){ #if it's not an attribute
if(array_key_exists("$key attr", $data)){
while(list($attr_name, $attr_value) = each($data["$key attr"])){
#echo "found attribute $attribute_name with value $attribute_value<br>";
$attr_value = &htmlspecialchars($attr_value, ent_quotes);
$attributes .= " $attr_name=\"$attr_value\"";
}
}

if(is_numeric($key)){
#echo "my current key ($key) is numeric. my parent key is '$prior_key'<br>";
$key = $prior_key;
}else{
#you can't have numeric keys at two levels in a row, so this is ok
#echo "checking to see if a numeric key exists in data.";
if(is_array($value) and array_key_exists(0, $value)){
# echo " it does! calling myself as a result of a numeric array.<br>";
$numeric_array = true;
$xml_serialized_string .= xml_serialize($value, $level, $key);
}
#echo "<br>";
}

if(!$numeric_array){
$xml_serialized_string .= str_repeat("\t", $level) . "<$key$attributes>";

if(is_array($value)){
$xml_serialized_string .= "\r\n" . xml_serialize($value, $level+1);
}else{
$inline = true;
$xml_serialized_string .= htmlspecialchars($value);
}

$xml_serialized_string .= (!$inline ? str_repeat("\t", $level) : "") . "</$key>\r\n";
}
}else{
#echo "skipping attribute record for key $key<br>";
}
}
if($level == 0){
$xml_serialized_string = "<?xml version=\"1.0\" ?>\r\n" . $xml_serialized_string;
return $xml_serialized_string;
}else{
return $xml_serialized_string;
}
}

class xml {
var $parser; #a reference to the xml parser
var $document; #the entire xml structure built up so far
var $current; #a pointer to the current item - what is this
var $parent; #a pointer to the current parent - the parent will be an array
var $parents; #an array of the most recent parent at each level

var $last_opened_tag;

function xml($data=null){
$this->parser = xml_parser_create();

xml_parser_set_option ($this->parser, xml_option_case_folding, 0);
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, "open", "close");
xml_set_character_data_handler($this->parser, "data");
# register_shutdown_function(array($this, 'destruct'));
}

function destruct(){
xml_parser_free($this->parser);
}

function parse($data){
$this->document = array();
$this->parent = $this->document;
$this->parents = array();
$this->last_opened_tag = null;
xml_parse($this->parser, $data);
return $this->document;
}

function open($parser, $tag, $attributes){
#echo "opening tag $tag<br>\n";
$this->data = "";
$this->last_opened_tag = $tag; #tag is a string
if(array_key_exists($tag, $this->parent)){
#echo "there's already an instance of '$tag' at the current level ($level)<br>\n";
if(is_array($this->parent[$tag]) and array_key_exists(0, $this->parent[$tag])){ #if the keys are numeric
#need to make sure they're numeric (account for attributes)
$key = count_numeric_items($this->parent[$tag]);
#echo "there are $key instances: the keys are numeric.<br>\n";
}else{
#echo "there is only one instance. shifting everything around<br>\n";
$temp = $this->parent[$tag];
unset($this->parent[$tag]);
$this->parent[$tag][0] = $temp;

if(array_key_exists("$tag attr", $this->parent)){
#shift the attributes around too if they exist
$temp = $this->parent["$tag attr"];
unset($this->parent["$tag attr"]);
$this->parent[$tag]["0 attr"] = $temp;
}
$key = 1;
}
$this->parent = $this->parent[$tag];
}else{
$key = $tag;
}
if($attributes){
$this->parent["$key attr"] = $attributes;
}

$this->parent[$key] = array();
$this->parent = $this->parent[$key];
array_unshift($this->parents, $this->parent);
}

function data($parser, $data){
#echo "data is '", htmlspecialchars($data), "'<br>\n";
if($this->last_opened_tag != null){
$this->data .= $data;
}
}

function close($parser, $tag){
#echo "close tag $tag<br>\n";
if($this->last_opened_tag == $tag){
$this->parent = $this->data;
$this->last_opened_tag = null;
}
array_shift($this->parents);
$this->parent = $this->parents[0];
}
}

function & xml_unserialize($xml){
$xml_parser = new xml();
$data = $xml_parser->parse($xml);
$xml_parser->destruct();
return $data;
}

function & xmlrpc_parse($request){
if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_parse', "<p>received the following raw request:</p>" . xmlrpc_show($request, 'print_r', true));
}
$data = &xml_unserialize($request);
if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_parse', "<p>returning the following parsed request:</p>" . xmlrpc_show($data, 'print_r', true));
}
return $data;
}

function & xmlrpc_prepare($data, $type = null){
if(is_array($data)){
$num_elements = count($data);
if((array_key_exists(0, $data) or !$num_elements) and $type != 'struct'){ #it's an array
if(!$num_elements){ #if the array is emptyempty
$returnvalue = array('array' => array('data' => null));
}else{
$returnvalue['array']['data']['value'] = array();
$temp = $returnvalue['array']['data']['value'];
$count = count_numeric_items($data);
for($n=0; $n<$count; $n++){
$type = null;
if(array_key_exists("$n type", $data)){
$type = $data["$n type"];
}
$temp[$n] = xmlrpc_prepare($data[$n], $type);
}
}
}else{ #it's a struct
if(!$num_elements){ #if the struct is emptyempty
$returnvalue = array('struct' => null);
}else{
$returnvalue['struct']['member'] = array();
$temp = $returnvalue['struct']['member'];
while(list($key, $value) = each($data)){
if(substr($key, -5) != ' type'){ #if it's not a type specifier
$type = null;
if(array_key_exists("$key type", $data)){
$type = $data["$key type"];
}
$temp[] = array('name' => $key, 'value' => xmlrpc_prepare($value, $type));
}
}
}
}
}else{ #it's a scalar
if(!$type){
if(is_int($data)){
$returnvalue['int'] = $data;
return $returnvalue;
}elseif(is_float($data)){
$returnvalue['double'] = $data;
return $returnvalue;
}elseif(is_bool($data)){
$returnvalue['boolean'] = ($data ? 1 : 0);
return $returnvalue;
}elseif(preg_match('/^\d{8}t\d{2}:\d{2}:\d{2}$/', $data, $matches)){ #it's a date
$returnvalue['datetime.iso8601'] = $data;
return $returnvalue;
}elseif(is_string($data)){
$returnvalue['string'] = htmlspecialchars($data);
return $returnvalue;
}
}else{
$returnvalue[$type] = htmlspecialchars($data);
}
}
return $returnvalue;
}

function & xmlrpc_adjustvalue($current_node){
if(is_array($current_node)){
if(isset($current_node['array'])){
if(!is_array($current_node['array']['data'])){
#if there are no elements, return an emptyempty array
return array();
}else{
#echo "getting rid of array -> data -> value<br>\n";
$temp = $current_node['array']['data']['value'];
if(is_array($temp) and array_key_exists(0, $temp)){
$count = count($temp);
for($n=0;$n<$count;$n++){
$temp2[$n] = &xmlrpc_adjustvalue($temp[$n]);
}
$temp = $temp2;
}else{
$temp2 = &xmlrpc_adjustvalue($temp);
$temp = array($temp2);
#i do the temp assignment because it avoids copying,
# since i can put a reference in the array
#php's reference model is a bit silly, and i can't just say:
# $temp = array(&xmlrpc_adjustvalue($temp));
}
}
}elseif(isset($current_node['struct'])){
if(!is_array($current_node['struct'])){
#if there are no members, return an emptyempty array
return array();
}else{
#echo "getting rid of struct -> member<br>\n";
$temp = $current_node['struct']['member'];
if(is_array($temp) and array_key_exists(0, $temp)){
$count = count($temp);
for($n=0;$n<$count;$n++){
#echo "passing name {$temp[$n][name]}. value is: " . show($temp[$n][value], var_dump, true) . "<br>\n";
$temp2[$temp[$n]['name']] = &xmlrpc_adjustvalue($temp[$n]['value']);
#echo "adjustvalue(): after assigning, the value is " . show($temp2[$temp[$n]['name']], var_dump, true) . "<br>\n";
}
}else{
#echo "passing name $temp[name]<br>\n";
$temp2[$temp['name']] = &xmlrpc_adjustvalue($temp['value']);
}
$temp = $temp2;
}
}else{
$types = array('string', 'int', 'i4', 'double', 'datetime.iso8601', 'base64', 'boolean');
$fell_through = true;
foreach($types as $type){
if(array_key_exists($type, $current_node)){
#echo "getting rid of '$type'<br>\n";
$temp = $current_node[$type];
#echo "adjustvalue(): the current node is set with a type of $type<br>\n";
$fell_through = false;
break;
}
}
if($fell_through){
$type = 'string';
#echo "fell through! type is $type<br>\n";
}
switch ($type){
case 'int': case 'i4': $temp = (int)$temp; break;
case 'string': $temp = (string)$temp; break;
case 'double': $temp = (double)$temp; break;
case 'boolean': $temp = (bool)$temp; break;
}
}
}else{
$temp = (string)$current_node;
}
return $temp;
}

function xmlrpc_getparams($request){
if(!is_array($request['methodcall']['params'])){
#if there are no parameters, return an emptyempty array
return array();
}else{
#echo "getting rid of methodcall -> params -> param<br>\n";
$temp = $request['methodcall']['params']['param'];
if(is_array($temp) and array_key_exists(0, $temp)){
$count = count($temp);
for($n = 0; $n < $count; $n++){
#echo "serializing parameter $n<br>";
$temp2[$n] = &xmlrpc_adjustvalue($temp[$n]['value']);
}
}else{
$temp2[0] = &xmlrpc_adjustvalue($temp['value']);
}
$temp = $temp2;
return $temp;
}
}

function xmlrpc_getmethodname($methodcall){
#returns the method name
return $methodcall['methodcall']['methodname'];
}

function xmlrpc_request($site, $location, $methodname, $params = null, $user_agent = null){
$site = explode(':', $site);
if(isset($site[1]) and is_numeric($site[1])){
$port = $site[1];
}else{
$port = 80;
}
$site = $site[0];

$data["methodcall"]["methodname"] = $methodname;
$param_count = count($params);
if(!$param_count){
$data["methodcall"]["params"] = null;
}else{
for($n = 0; $n<$param_count; $n++){
$data["methodcall"]["params"]["param"][$n]["value"] = $params[$n];
}
}
$data = xml_serialize($data);

if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_request', "<p>received the following parameter list to send:</p>" . xmlrpc_show($params, 'print_r', true));
}
$conn = fsockopen ($site, $port); #open the connection
if(!$conn){ #if the connection was not opened successfully
if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_request', "<p>connection failed: couldn't make the connection to $site.</p>");
}
return array(false, array('faultcode'=>10532, 'faultstring'=>"connection failed: couldn't make the connection to $site."));
}else{
$headers =
"post $location http/1.0\r\n" .
"host: $site\r\n" .
"connection: close\r\n" .
($user_agent ? "user-agent: $user_agent\r\n" : '') .
"content-type: text/xml\r\n" .
"content-length: " . strlen($data) . "\r\n\r\n";

fputs($conn, "$headers");
fputs($conn, $data);

if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_request', "<p>sent the following request:</p>\n\n" . xmlrpc_show($headers . $data, 'print_r', true));
}

#socket_set_blocking ($conn, false);
$response = "";
while(!feof($conn)){
$response .= fgets($conn, 1024);
}
fclose($conn);

#strip headers off of response
$data = xml_unserialize(substr($response, strpos($response, "\r\n\r\n")+4));

if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_request', "<p>received the following response:</p>\n\n" . xmlrpc_show($response, 'print_r', true) . "<p>which was serialized into the following data:</p>\n\n" . xmlrpc_show($data, 'print_r', true));
}
if(isset($data['methodresponse']['fault'])){
$return = array(false, xmlrpc_adjustvalue($data['methodresponse']['fault']['value']));
if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_request', "<p>returning:</p>\n\n" . xmlrpc_show($return, 'var_dump', true));
}
return $return;
}else{
$return = array(true, xmlrpc_adjustvalue($data['methodresponse']['params']['param']['value']));
if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_request', "<p>returning:</p>\n\n" . xmlrpc_show($return, 'var_dump', true));
}
return $return;
}
}
}

function xmlrpc_response($return_value, $server = null){
$data["methodresponse"]["params"]["param"]["value"] = $return_value;
$return = xml_serialize($data);

if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_response', "<p>received the following data to return:</p>\n\n" . xmlrpc_show($return_value, 'print_r', true));
}

header("connection: close");
header("content-length: " . strlen($return));
header("content-type: text/xml");
header("date: " . date("r"));
if($server){
header("server: $server");
}

if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_response', "<p>sent the following response:</p>\n\n" . xmlrpc_show($return, 'print_r', true));
}
echo $return;
}

function xmlrpc_error($faultcode, $faultstring, $server = null){
$array["methodresponse"]["fault"]["value"]["struct"]["member"] = array();
$temp = $array["methodresponse"]["fault"]["value"]["struct"]["member"];
$temp[0]["name"] = "faultcode";
$temp[0]["value"]["int"] = $faultcode;
$temp[1]["name"] = "faultstring";
$temp[1]["value"]["string"] = $faultstring;

$return = xml_serialize($array);

header("connection: close");
header("content-length: " . strlen($return));
header("content-type: text/xml");
header("date: " . date("r"));
if($server){
header("server: $server");
}
if(defined('xmlrpc_debug') and xmlrpc_debug){
xmlrpc_debug('xmlrpc_error', "<p>sent the following error response:</p>\n\n" . xmlrpc_show($return, 'print_r', true));
}
echo $return;
}

function xmlrpc_convert_timestamp_to_iso8601($timestamp){
#takes a unix timestamp and converts it to iso8601 required by xmlrpc
#an example iso8601 datetime is "20010822t03:14:33"
return date("ymd\th:i:s", $timestamp);
}

function xmlrpc_convert_iso8601_to_timestamp($iso8601){
return strtotime($iso8601);
}

function count_numeric_items($array){
return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0;
}

function xmlrpc_debug($function_name, $debug_message){
$globals['xmlrpc_debug_info'][] = array($function_name, $debug_message);
}

function xmlrpc_debug_print(){
if($globals['xmlrpc_debug_info']){
echo "<table border=\"1\" width=\"100%\">\n";
foreach($globals['xmlrpc_debug_info'] as $debug){
echo "<tr><th style=\"vertical-align: top\">$debug[0]</th><td>$debug[1]</td></tr>\n";
}
echo "</table>\n";
unset($globals['xmlrpc_debug_info']);
}else{
echo "<p>no debugging information available yet.</p>";
}
}

function xmlrpc_show($data, $func = "print_r", $return_str = false){
ob_start();
$func($data);
$output = ob_get_contents();
ob_end_clean();
if($return_str){
return "<pre>" . htmlspecialchars($output) . "</pre>\n";
}else{
echo "<pre>", htmlspecialchars($output), "</pre>\n";
}
}

?>

服务端程序例子,server.php
复制代码 代码如下:

<?
include 'xml-rpc.inc.php';
//定义可被远程调用的方法
$xmlrpc_methods=array();
$xmlrpc_methods['insertrecords']='insertrecords';

//获得用户传入的方法名和参数
$xmlrpc_request = xmlrpc_parse($http_raw_post_data);
$methodname = xmlrpc_getmethodname($xmlrpc_request);
$params = xmlrpc_getparams($xmlrpc_request);

if (!isset($xmlrpc_methods[$methodname])){
xmlrpc_error('1',"你所调用的方法不存在");
}else {
$xmlrpc_methods[$methodname]($params);
}
function insertrecords($params){
if (emptyempty($params)){
xmlrpc_error('2',"参数出错");
}
xmlrpc_response(xmlrpc_prepare('http://www.emtit.com'));
}
?>

php客户端调用服务端方法例子
复制代码 代码如下:

<?php
include_once 'xml-rpc.inc';
$params=array(2,3);
$result=xmlrpc_request("127.0.0.1","/services/server.php","insertrecords",$params);//服务端文件放在services文件夹下
print_r($result);
?>

结果会显示www.emtiit.com