Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : XML-RPC Functions

XML-RPC Functions

Introduction

These functions can be used to write XML-RPC servers and clients. You can find more information about XML-RPC at » http://www.xmlrpc.com/, and more documentation on this extension and its functions at » http://xmlrpc-epi.sourceforge.net/.

Warning:

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.

Requirements

No external libraries are needed to build this extension.

Installation

XML-RPC support in PHP is not enabled by default. You will need to use the --with-xmlrpc[=DIR] configuration option when compiling PHP to enable XML-RPC support. This extension is bundled into PHP as of 4.1.0.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 338. XML-RPC configuration options

Name Default Changeable Changelog
xmlrpc_errors "0" PHP_INI_SYSTEM Available since PHP 4.1.0.
xmlrpc_error_number "0" PHP_INI_ALL Available since PHP 4.1.0.


For further details and definitions of the PHP_INI_* constants, see the Appendix I, php.ini directives.

Resource Types

This extension defines a XML-RPC server resource returned by xmlrpc_server_create().

Predefined Constants

This extension has no constants defined.

Table of Contents

xmlrpc_decode_request — Decodes XML into native PHP types
xmlrpc_decode — Decodes XML into native PHP types
xmlrpc_encode_request — Generates XML for a method request
xmlrpc_encode — Generates XML for a PHP value
xmlrpc_get_type — Gets xmlrpc type for a PHP value
xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault
xmlrpc_parse_method_descriptions — Decodes XML into a list of method descriptions
xmlrpc_server_add_introspection_data — Adds introspection documentation
xmlrpc_server_call_method — Parses XML requests and call methods
xmlrpc_server_create — Creates an xmlrpc server
xmlrpc_server_destroy — Destroys server resources
xmlrpc_server_register_introspection_callback — Register a PHP function to generate documentation
xmlrpc_server_register_method — Register a PHP function to resource method matching method_name
xmlrpc_set_type — Sets xmlrpc type, base64 or datetime, for a PHP string value

Code Examples / Notes » ref.xmlrpc

hfuecks

You can pass PHP errors with the XML-RPC extension as described here: http://www.zend.com/lists/php-dev/200107/msg00642.html

sjtirtha

To install xml-rpc feature on Windows, you need to have "php_xmlrpc.dll" on your "/extensions" Folder.
And you need to enable it on "php.ini".
You need also library from http://xmlrpc-epi.sourceforge.net .
to make your code simply.
Look the examples at http://www.devshed.com/Server_Side/PHP/XMLRPCwithPHP/page1.html .


martin dot rode

To connect to a python xmlrpc server I use:
function do_call($host, $port, $request) {
 
   $url = "http://$host:$port/";
   $header[] = "Content-type: text/xml";
   $header[] = "Content-length: ".strlen($request);
   
   $ch = curl_init();  
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_TIMEOUT, 1);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
   
   $data = curl_exec($ch);      
   if (curl_errno($ch)) {
       print curl_error($ch);
   } else {
       curl_close($ch);
       return $data;
   }
}
$request = xmlrpc_encode_request('add', array(3, 4));
$response = do_call($host, $port, $request);


09-mar-2006 08:47

This XML-RPC Service makes the use XML-RPC very esay.
<?php
/**
* function myfun() returns  
*@return array
*/
function myfunc(){
   return $some_array;
}
$ws = new XML_RPC_Server();
$ws->registerFunction('myfunc');
$ws->run();
?>
http://www.pure-php.de/node/31
It creates also a simple docu.
http://www.pure-php.com/php/service.php?doc


hfuecks

This extension does not handle the process of making making XML-RPC client requests via HTTP; it only prepares the XML-RPC request payload.
This differs from many other XML-RPC implementations but offers greater flexibility, allowing SSL connections, authentication headers and XML-RPC via other transports like SMTP.


steve

There's a handy library by Keith Devens (version 2.2.1) at
http://www.keithdevens.com/software/xmlrpc/
Here is a sample client. It remotely calls sample.sumAndDifference
with two parameters (3 and 5).
It returns:
sum => 8
difference => -2
<?php
include ("kd_xmlrpc.php");
// define("XMLRPC_DEBUG", 0);    // Set to 1 for handy debugging
$method = "sample.sumAndDifference";
$params = XMLRPC_prepare(array(3,5));
$site = "xmlrpc-c.sourceforge.net";
$location = "/api/sample.php";
list($success, $result) = XMLRPC_request( $site, $location, $method, $params );
// XMLRPC_debug_print();    // uncomment for debugging
foreach ( $result as $key => $value ) {
         echo(" $key => $value \n");
}
?>


astrolox

The PHP XML-RPC project at SourceForge makes life a hell of a lot easier. However, the project uses some function names which are identical to thoses provided by the XML-RPC extention.
If you are on a server with XML-RPC extension compiled in but wish to use the PHP based version then you will have to rename some of the functions.
I notice that sourceforce says there is activity on the project in 2005 but the last release was January 12, 2003.
I recommend that you use this not so friendly PHP extention if available. However this sourceforce project is still a good idea if you don't control which extenions are be available on the server.
http://phpxmlrpc.sourceforge.net/


jerome delamarche

The documentation lacks an example that shows how to send a fault in a response. Here is how to do it:
$args = array("faultCode" => $errcode, "faultString" => $errmsg);
$resp = xmlrpc_encode_request(NULL,$args);
//echo $resp;


php dot net et athens musician det net

The devshed article and tutorial has been moved to the following url as of July 5, 2006
http://www.devshed.com/c/a/PHP/Using-XMLRPC-with-PHP/


ravan_n

Refer to the below link for documentation / latest releases of the package.
http://xmlrpc-epi.sourceforge.net/main.php?t=php_about


swunderlin

pear hs an XML_RPC package, if you can't recompile your php:
http://pear.php.net/package/XML_RPC


php

On "datetime" values:
If you implement an XML-RPC server with these functions and a client calls a method on your server, sending a datetime as parameter (in ISO 8601 format, as specified at http://www.xmlrpc.com/spec), the PHP XML-RPC will pass your registered server method an object as parameter. That object, for example, looks like:
obj->type="datetime"
obj->scalar="20040420T13:32:40"
obj->timestamp=1082460760
If you do xmlrpc_get_type(obj), it will return "datetime", so presumably that function just returns the value of 'type'. 'scalar' seems to be the on-the-wire representation of the datetime (ISO 8601, exactly as received). 'timestamp' appears to be the ISO value in 'scalar' converted into a normal PHP timestamp (i.e. Unix time_t).
Note on 'scalar': Using a MySQL DB, we did something like  "select blah where start_time >= $obj->scalar ;". That actually worked and returned expected results, so MySQL appears to handle that ISO 8601 format correctly.


nospam

Note that you do need the iconv module installed to use the XML-RPC extension (see: http://www.php.net/manual/en/ref.iconv.php)

mboeren

Just a quick addition to my previous xmlrpc_client class: since you cannot use remote methods containing capital letters or methods from subhandlers (like 'system.listMethods()'), I added a 'call(...)' method to the class.
<?php
   // this method should be copy/pasted in the
   // xmlrpc_client class
   function call($function)
   {
       $return = NULL;
       $argv = func_get_args();
       array_shift($argv); // remove function argument
       $this->__call($function, $argv, &$return);
       return $return;
   }
   // now, you can also do
   $result = $client->call('system.listMethods');
   $sum = client->call('add', '1', '2');
?>


steph

It took me a while to get a client together without external libraries.  This very basic client/server pair works on my home set-up - hopefully it will save the next xml-rpc virgin some grief.
/* clienttest.php */
<?php
function do_call($host, $port, $request) {

$fp = fsockopen($host, $port, $errno, $errstr);
$query = "POST /home/servertest.php HTTP/1.0\nUser_Agent: My Egg Client\nHost: ".$host."\nContent-Type: text/xml\nContent-Length: ".strlen($request)."\n\n".$request."\n";
if (!fputs($fp, $query, strlen($query))) {
$errstr = "Write error";
return 0;
}
$contents = '';
while (!feof($fp)) {
$contents .= fgets($fp);
}
fclose($fp);
return $contents;
}
$host = 'localhost';
$port = 80;
$request = xmlrpc_encode_request('cycle', 'egg');
$response = do_call($host, $port, $request);
/* do something with $response, e.g. print it */
?>
/* servertest.php */
<?php
function lifecycle($method, $params) {
/* $method = 'cycle', $params = (array of) request parameter(s); $data is also passed from xmlrpc_server_call_method, if we had any data to pass */
switch($params[0]) {
case 'egg':
$reply = 'All eggs will be birds one day.';
break;
default:
$reply = 'That must have been an otheregg';
}
return $reply;
}
$server = xmlrpc_server_create();
/* register the 'external' name and then the 'internal' name */
xmlrpc_server_register_method($server, "cycle", "lifecycle");
$request = $HTTP_RAW_POST_DATA; // no you don't need 'always on', and no $_POST doesn't work.
/* the parameters here are 'server, xml-string and user data'.  There's supposed to be an optional 'output options' array too, but I can't get it working :( hence header() call */
$response = xmlrpc_server_call_method($server, $request, null);
header('Content-Type: text/xml');
print $response;
xmlrpc_server_destroy($server);
?>


giunta dot gaetano

If you need to use this extension but are stuck on a server where it can not be installed, the php-xmlrpc library found at http://phpxmlrpc.sourceforge.net includes an emulation layer that aims to be 100% compatible with the API of the native extension (as part of the "extras" package since version 0.2).
This means your code should be able to run unmodified on top of the php-xmlrpc library. Of course performance will be at least an order of magnitude worse...


daniel

If you need a tutorial on the XML-RPC-Extension go to devshed:
 http://www.devshed.com/Server_Side/PHP/XMLRPCwithPHP/page1.html


bmichael

If anyone is interested in making XMLRPC requests directly from the client, I have been able to get xmlrpc to
work with vcXMLRPC javascript backend.
After about 1 week of scanning the market, I found this solution to be the best on Javascript back end.  It uses the Microsoft.HTTP activeX control for IE, or HTTPRequest Object for Mozilla.
You include vc(Virtual Cowboys) vcXMLRPC.js file into your pages and make the rpc calls from with javascript to create the requests.
It works both ways.
Two Notes:
I have tested it on IE 6.02 and you need to change lines in ProcessRequest :
function to read:
 dom = this.getObject("XMLDOM",http.responseText);
and change the getObject function to use the latest ActiveX Control:
MSXML2.XMLHTTP.3.0  (or 4.0)
MSXML2.DOMDocument.3.0  (or 4.0)
The controls are found on MSDN in the Web Services -> XML area.
As another note, you DO NOT NEED the rpcproxy.cgi script to use this.  That is a proxy script to get around JS Security.  You can use PHP to build the proxy.  But, I was able to get the CGI working with GCC compiler on Solaris (change the -KPCI, depend and -x03 optimizer settings in the Makefile )


mboeren

I use the following code (requires the overload extension) to make developing clients easier:
<?php
include("utils/utils.php"); // from xmlrpc-epi utils
/*
Usage:
   $client = new xmlrpc_client("http://localhost:7080");
   print $client->echo('x')."\n";
   print $client->add(1, 3)."\n";
*/
class xmlrpc_client
{
   var $url;
   var $urlparts;
   function xmlrpc_client($url)
   {
       $this->url = $url;
       $this->urlparts = parse_url($this->url);
       foreach(array('scheme', 'host', 'user', 'pass', 'path',
                     'query', 'fragment')
               as $part) {
           if (!isset($this->urlparts[$part])) {
               $this->urlparts[$part] = NULL;
               }
           }
   }
   function __call($function, $arguments, &$return)
   {
       $requestprms['host'] = $this->urlparts['host'];
       $requestprms['port'] = $this->urlparts['port'];
       $requestprms['uri'] = $this->urlparts['path'];
       $requestprms['method'] = $function;
       $requestprms['args'] = $arguments;
       $requestprms['debug'] = 0;
       $requestprms['timeout'] = 0;
       $requestprms['user'] = NULL;
       $requestprms['pass'] = NULL;
       $requestprms['secure'] = 0;
       $result = xu_rpc_http_concise($requestprms);
       if (is_array($result) && isset($result['faultCode'])) {
           print('Error in xmlrpc call \''.$function.'\''."\n");
           print('  code   : '.$result['faultCode']."\n");
           print('  message: '.$result['faultString']."\n");
           return false;
           }
       $return = $result;
       return true;
   }
}
overload('xmlrpc_client');
?>


john # curioussymbols com

I couldn't make the 'xmlrpc_errors' php.ini setting do anything
noticeable (PHP 4.3.11), so I used the following code to report errors
from my XMLRPC server. Hope it's helpful for someone.
<?php
function return_xmlrpc_error($errno,$errstr,$errfile=NULL,$errline=NULL
      ,$errcontext=NULL){
global $xmlrpc_server;
if(!$xmlrpc_server)die("Error: $errstr in '$errfile', line '$errline'");
header("Content-type: text/xml; charset=UTF-8");
print(xmlrpc_encode(array(
'faultCode'=>$errno
,'faultString'=>"Remote XMLRPC Error from
 ".$_SERVER['HTTP_HOST'].": $errstr in at $errfile:$errline"
)));
die();
}
set_error_handler('return_xmlrpc_error');
?>
In my server function, I just trigger_error("message",E_USER_ERROR)]
if something can't be completed.
Then on the client side,
<?php
$data =& xmlrpc_decode($response['body']);
if(xmlrpc_is_fault($data)){
trigger_error($data['faultString'],E_USER_ERROR);
}
?>


mistcat attyatatat phreaker dootttt net

Hope this saves somone some frustration:
As of php 4.3.1 and xmlrpc-epi-php-0.51 php would return a content type text/html instead of text/xml in its responses.  this is a bad thing.  Perl's XMLRPC::Lite for instance will not like you if you do this.  Happily the solution is simple:
header("Content-Type: text/xml");
Happy Hunting.
-Nate


handco

Hi,
A little snippet to implement OO XML RPC Server.
File RPCPlugin.php :
class RPCPlugins {

private $plugins;

function __construct ($pathname, $rpcServer) {
$d = dir($pathname);
while (($file = $d->read()) !== false) {
if (ereg('(.*)\.php$', $file, $regs)) {
include_once ($pathname . '/' . $file);
$class=$regs[1];
$this->plugins = new $class($rpcServer);
}
}
}

}
class RPCPlugin {

private $_rpcServer;

function __construct($rpcServer) {
$this->_rpcServer = $rpcServer;

$methods = get_class_methods($this);

foreach ($methods as $method) {
if (substr($method, 0,1) != '_') {
xmlrpc_server_register_method($rpcServer,get_class($this) . "." . $method,array(&$this,$method));
}
}

}

}
An example of plugin in plugins/Test.php  :
class Test extends RPCPlugin {


function HelloWorld ($method, $params) {
return "Hello World --->>" . $params[0];
}

}
Now the real server :
require_once 'RPCPlugin.php';

$rpcServer = xmlrpc_server_create();

$plugins = new RPCPlugins(realpath('plugins/'), $rpcServer);

$resp = xmlrpc_server_call_method($rpcServer,$HTTP_RAW_POST_DATA,null);
if ($resp) {
header ('Content-Type: text/xml');
echo $resp;
}
xmlrpc_server_destroy($rpcServer)
Then you can call ethod by classname.method.
For this sample Test.HelloWorld
Hn'Co


frank

here's how to install it on windows (so it actually works):
- php.ini > enable "php_xmlrpc.dll" in extensions.
- php.ini > make sure "extension_dir" is set correctly to find the dll in your php installation dir /extensions.
- copy iconv.dll from your php install dir /dlls to a directory in your path (ex: c:/windows).
if you got some errors while launching apache prior to trying this I suggest you reboot your machine first... sounds weird I know, but remember... you're running Windowz.
Have fun


keithno dot spamthornhill

for others attempting the same thing, here is what a function would look like if you wanted to send a base64 encoded file from a client and then save it onto the server. the other code necessary to call this function via an RPC is available in other comments so i won't repeat it.
parameters:
1 - name of file
2 - base64 encoded data of file
note the use of $file_data->scalar
<?
function sendFile($method_name, $params, $user_data) {
$file = "/somedir/" . $params[0];
$file_data = $params[1];
$fh = @fopen($file, "wb");
if ($fh) {
if (@fwrite($fh, $file_data->scalar)) {
$msg = "success msg";
} else {
$msg = "couldn't write to file";
}
fclose($fh);
return $msg;
} else {
return "couldn't open file";
}
}
?>


ivanr

For a really easy way to use this XML-RPC extension take a look at
XML-RPC Class Server (http://www.webkreator.com/php/xcs/)
It automatically creates servers out of PHP classes. Creating clients is almost as easy, especially with the recent addition of the overload extension to PHP (see http://www.php.net/manual/en/ref.overload.php).


hfuecks

Anyone interested in PHP-GTK talking to an XML-RPC server:
http://www.pinkgoblin.com/gtk2xmlrpc.php


nic

An alternative XML-RPC implementation is available at http://xmlrpc.usefulinc.com - it's written in PHP so you can use it on servers for which you don't have the luxury of rebuilding PHP on.
nic


handco

An alternative to $HTTP_RAW_POST_DATA use :
$request = file_get_contents('php://input');


digibrisk

Adding to what giunta dot gaetano at sea-aeroportimilano dot it and astrolox at lawyersonline dot co dot uk said about the Sourceforge PHP XML-RPC project: You can probably use function_exists() to determine whether the extension is installed so you don't have to incur performance costs. If it's not installed, then the function won't exist, and function_exists() returns false. You can then fall back on the alternative library if that's the case. For example:
<?php
if(!function_exists("xmlrpc_server_create")) {
   // include necessary files.
}
?>


cmv

"Latest releases" is a bit redundant, since this extension is bundled into PHP (as of 4.1.0).  You don't need to download anything from sourceforge to make this work.  Just compile PHP with the --with-xmlrpc flag.
The site http://xmlrpc-epi.sourceforge.net/ is useful, however, for documentation.


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker