PHP xml-rpc Remote Call _php tutorial

Source: Internet
Author: User
Tags iso 8601 xml parser
Copy CodeThe code is as follows:
/*
The XML-RPC library, which is found on the Internet, is useful for developing small external communication interfaces.
*/

Function & Xml_serialize ($data, $level = 0, $prior _key = NULL) {
#assumes a hash, keys is the variable names
$xml _serialized_string = "";
while (list ($key, $value) = each ($data)) {
$inline = false;
$numeric _array = false;
$attributes = "";
#echo "My current key was ' $key ', called with prior key ' $prior _key '
";
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
";
$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 '
";
$key = $prior _key;
}else{
#you can ' t has numeric keys at levels-a row, so the 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.
";
$numeric _array = true;
$xml _serialized_string. = Xml_serialize ($value, $level, $key);
}
#echo "
";
}

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): ""). " \ r \ n ";
}
}else{
#echo "Skipping attribute record for key $key
";
}
}
if ($level = = 0) {
$xml _serialized_string = " \ 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
var $current; #a pointer to the current item-what are this
var $parent; #a pointer to the current parent-the parent would be an array
var $parents; #an array of the most recent.

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
\ 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)
\ 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 is $key instances:the keys are numeric.
\ n ";
}else{
#echo "There is only one instance. Shifting everything around
\ 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), "'
\ n ";
if ($this->last_opened_tag! = NULL) {
$this->data. = $data;
}
}

function Close ($parser, $tag) {
#echo "Close tag $tag
\ 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 ', "

Received the following raw request:

" . Xmlrpc_show ($request, ' Print_r ', true));
}
$data = &xml_unserialize ($request);
if (defined (' Xmlrpc_debug ') and Xmlrpc_debug) {
Xmlrpc_debug (' Xmlrpc_parse ', "

Returning the following parsed request:

" . 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 is no elements, return an Emptyempty array
return Array ();
}else{
#echo "Getting rid of array-data-and value
\ 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 + +) {
$temp 2[$n] = &xmlrpc_adjustvalue ($temp [$n]);
}
$temp = $temp 2;
}else{
$temp 2 = &xmlrpc_adjustvalue ($temp);
$temp = Array ($temp 2);
#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 is no members, return an Emptyempty array
return Array ();
}else{
#echo "Getting rid of struct-member
\ 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). "
\ n ";
$temp 2[$temp [$n] [' name ']] = &xmlrpc_adjustvalue ($temp [$n] [' value ']);
#echo "Adjustvalue (): After assigning, the value is". Show ($temp 2[$temp [$n] [' name ']], var_dump, true). "
\ n ";
}
}else{
#echo "Passing name $TEMP [name]
\ n ";
$temp 2[$temp [' name ']] = &xmlrpc_adjustvalue ($temp [' value ']);
}
$temp = $temp 2;
}
}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 '
\ n ";
$temp = $current _node[$type];
#echo "Adjustvalue (): The current node was set with a type of $type
\ n ";
$fell _through = false;
Break
}
}
if ($fell _through) {
$type = ' string ';
#echo "Fell through! Type is $type
\ 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 is no parameters, return an Emptyempty array
return Array ();
}else{
#echo "Getting rid of methodcall, params, param
\ 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
";
$temp 2[$n] = &xmlrpc_adjustvalue ($temp [$n] [' value ']);
}
}else{
$temp 2[0] = &xmlrpc_adjustvalue ($temp [' value ']);
}
$temp = $temp 2;
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 ', "

Received The following parameter list to send:

" . Xmlrpc_show ($params, ' Print_r ', true));
}
$conn = Fsockopen ($site, $port); #open the connection
if (! $conn) {#if The connection is not opened successfully
if (defined (' Xmlrpc_debug ') and Xmlrpc_debug) {
Xmlrpc_debug (' Xmlrpc_request ', "

Connection failed:couldn ' t make the Connection to $site.

");
}
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 ', "

Sent the following request:

\ 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 ', "

Received the following response:

\ n ". Xmlrpc_show ($response, ' Print_r ', true). "

Which was serialized into the following data:

\ 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 ', "

Returning:

\ 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 ', "

Returning:

\ 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 ', "

Received the following data to return:

\ 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 ', "

Sent the following response:

\ 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 ', "

Sent the following error response:

\ 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 ($iso 8601) {
Return Strtotime ($iso 8601);
}

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 "



\ n "; foreach ($GLOBALS [' Xmlrpc_debug_info '] as $debug) {echo ' \ n "; } echo "
$debug [0] $debug [1]
\ n ";
unset ($GLOBALS [' xmlrpc_debug_info ']);
}else{
echo "

No debugging information available yet.

";
}
}

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 "
" . Htmlspecialchars ($output). "
\ n ";
}else{
echo "
", Htmlspecialchars ($output),"
\ n ";
}
}

?>

Examples of server-side programs, server.php
Copy CodeThe code is as follows:
Include ' xml-rpc.inc.php ';
Define a method that can be called remotely
$xmlrpc _methods=array ();
$xmlrpc _methods[' insertrecords ']= ' insertrecords ';

Get user-passed method names and parameters
$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 ', "the method you are calling does not exist");
}else {
$xmlrpc _methods[$methodName] ($params);
}
function Insertrecords ($params) {
if (Emptyempty ($params)) {
Xmlrpc_error (' 2 ', "parameter Error");
}
Xmlrpc_response (Xmlrpc_prepare (' http://www.emtit.com '));
}
?>

PHP client Invoke service-side Method Example
Copy CodeThe code is as follows:
Include_once ' Xml-rpc.inc ';
$params =array (2,3);
$result =xmlrpc_request ("127.0.0.1", "/services/server.php", "Insertrecords", $params);//server file is placed under the Services folder
Print_r ($result);
?>

The results will show www.emtiit.com

http://www.bkjia.com/PHPjc/319869.html www.bkjia.com true http://www.bkjia.com/PHPjc/319869.html techarticle Copy the code as follows:? PHP/* XML-RPC Library from the Internet is useful for developing small external communication interfaces */function while (list ($key, $value) = each ($data)) {$inline = fa: .

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.