PEAR is archived and read-only

This mirror preserves historical PEAR package releases and metadata so existing references remain available.

Home » Web Services » XML_RPC2 » Manual

PHP5 implementation of the XML-RPC protocol. This is a "PHP5 only" implementation of the XMLRPC protocol. This package provides the client and the server side of the protocol. An optimized cache is also available for both parts. As a client library, XML_RPC2 is capable of creating a proxy class which exposes the methods exported by the server. As a server library, XML_RPC2 is capable of exposing methods from a class or object instance, seamlessly exporting local methods as remotely callable procedures.

Introduction

Introduction – Description XML_RPC2 is a "PHP5 only" implementation of the XMLRPC protocol. This package provides the client and the server side of the protocol. An optimized cache is also available for both parts. As a client library, XML_RPC2 is capable of creating a proxy class which exposes the methods exported by the server. So it's very easy and natural to call XMLRPC exported methods. Like in Python language, the classic way to use XML_RPC2 client side is : We make a XML_RCP2_Client object with server informations as arguments. In a classic way, we call a method of this object. Then, the method call is XMLRPC encoded, sent to the server, the response is decoded into PHP native types and we get the result of the call (all this logic is made by the library in a completely transparent way). As a server library, XML_RPC2 is capable of exposing methods from a class or object instance, seamlessly capable of exposing methods from a class or object instance, seamlessly exporting local methods as remotely callable procedures. Method signatures are automatically determined and checked by using the reflection API and PHPDOC comments. An automatic documentation about XMLRPC exported methods is dynamically built and available at the server URL (with a simple HTTP GET). For both sides, an optimized cache based on Cache_Lite can be set. It can be really usefull especially on public XMLRPC servers. Requirements XML_RCP2 need PHP5 and the CURL extension. To avoid in next version, the CURL dependency, we are waiting for a PHP5 E_STRICT PEAR module for HTTP_Request. If you want to use the integrated cache, you will also need the Cache_Lite PEAR module but it's of course an optional dependency. XML_RPC2 can use two backends for the XMLRPC encoding/decoding : XMLRPCEXT, which of course need this PHP extension (probably the better choice but it's an additional dependency) ; PHP, which doesn't need the XMLRPCEXT extension at all (this is full PHP but slower). A first example of the client side use Let's start with a XMLRPC call to the pear.php.net XMLRPC server : <?phprequire_once 'XML/RPC2/Client.php';$options = array(    'prefix' => 'package.');// We make the XML_RPC2_Client object (as the backend is not specified, XMLRPCEXT// will be used if available (full PHP else))$client = XML_RPC2_Client::create('http://pear.php.net/xmlrpc.php', $options);try {    // Because of the prefix specified in the $options array, indeed,  we will call    // the package.info() method with a single argument (the string 'XML_RPC2')    $result = $client->info('XML_RPC2');    // $result is a complex PHP type (no XMLRPC decoding needed, it's already done)    print_r($result);} catch (XML_RPC2_FaultException $e) {    // The XMLRPC server returns a XMLRPC error    die('Exception #' . $e->getFaultCode() . ' : ' . $e->getFaultString());} catch (Exception $e) {    // Other errors (HTTP or networking problems...)    die('Exception : ' . $e->getMessage());}?> A first example of the server side use Let's build a XMLRPC "echo server" : <?phprequire_once 'XML/RPC2/Server.php';// Let's define a class with public static methods// PHPDOC comments are really important because they are used for automatic// signature checkingclass EchoServer {    /**     * echoes the message received     *     * @param string  Message     * @return string The echo     */    public static function echoecho($string) {        return $string;    }}$options = array(    'prefix' => 'test.' // we define a sort of "namespace" for the server);// Let's build the server object with the name of the Echo class $server = XML_RPC2_Server::create('EchoServer', $options);$server->handleCall();?> If you do a simple HTTP GET on the server URL, you will get an automatic HTML documentation about the echoecho function. If you make a XMLRPC client request on the same URL about the "test.echoecho()" method (with one argument), you will get your argument as a response. If you call another method or with a bad arguments number, you will get an error (because of automatic method signature checking). A first example of the client side use (with integrated cache) As the caching process is completely transparent, this is very similar to the standard client side use : <?phprequire_once 'XML/RPC2/CachedClient.php';$options = array(    'prefix' => 'package.',    'cacheDebug' => false, // with cacheDebug set to true, it's very easy                           // to get an indication about the cache using (or not)    'cacheOptions' => array(        'cacheDir' => '/tmp/',        'lifetime' => 3600,      // during this lifetime, the local cache will be used         'cacheByDefault' => true // all methods call will be cached                                 // (but a more precise way is possible)    ));// We make the XML_RPC2_CachedClient object (same syntax than XML_RPC2_Client)$client = XML_RPC2_CachedClient::create('http://pear.php.net/xmlrpc.php', $options);try {    // First call, the cache won't be used    $result = $client->info('XML_RPC2');    print_r($result);    // Second call, the cache will be used  (in a transparent way) and no    // additional HTTP request will be sent to the server    $result = $client->info('XML_RPC2');    print_r($result);} catch (XML_RPC2_FaultException $e) {    // The XMLRPC server returns a XMLRPC error    die('Exception #' . $e->getFaultCode() . ' : ' . $e->getFaultString());} catch (Exception $e) {    // Other errors (HTTP or networking problems...)    die('Exception : ' . $e->getMessage());}?> A first example of the server side use (with integrated cache) As the caching process is completely transparent, this is very similar to the standard server side use : <?phprequire_once 'XML/RPC2/CachedServer.php';// Let's define a class with public static methods// PHPDOC comments are really important because they are used for automatic// signature checking// IMPORTANT : note the @xmlrpc.caching PHPDOC tags to indicate// that the method has to be cachedclass EchoServer {    /**     * echoes the message received     *     * @param string  Message     * @return string The echo     * @xmlrpc.caching true     */    public static function echoecho($string) {        return $string;    }}$options = array(    'prefix' => 'test..',    'cacheDebug' => false, // with cacheDebug set to true, it's very easy                           // to get an indication about the cache using (or not)    'cacheOptions' => array(        'cacheDir' => '/tmp/',        'lifetime' => 3600,        'cacheByDefault' => false // we don't cache by default (only methods with @xmlrpc.caching true)    ));$server = XML_RPC2_CachedServer::create('EchoServer', $options);  $server->handleCall();?>

Client Side

Client Side – Introduction about the XML_RPC2 client side usage Thanks to PHP5, it's really easy to do XMLRPC client requests with XML_RPC2. The usage is really straightforward. First, you include 'XML/RPC2/Client.php' file (only this one). <?phprequire_once 'XML/RPC2/Client.php';?> Second, you make an assocative arrays of options to tune XML_RPC2 (prefix, proxy, manual backend choice...). <?php$options = array(    'prefix' => 'package.');?> Third, you make a XML_RPC2_Client object with the server URL and the with the options array. <?php$client = XML_RPC2_Client::create('http://pear.php.net/xmlrpc.php', $options);?> Then, you send your request by calling the server method as it was a local method of the $client object. <?php$result = $client->info('XML_RPC2');?> This single line will encode a XMLRPC client request for the package.info() (prefix + method name) method with a single argument (the string 'XML_RPC2'), will send the request over HTTP to the server and will decode the response into PHP native types. With a single line ! Of course, to catch server errors, you have to add a few lines around you client call like for example : <?phptry {    $result = $client->info('XML_RPC2');     print_r($result);} catch (XML_RPC2_FaultException $e) {    // The XMLRPC server returns a XMLRPC error    die('Exception #' . $e->getFaultCode() . ' : ' . $e->getFaultString());} catch (Exception $e) {      // Other errors (HTTP or networking problems...)    die('Exception : ' . $e->getMessage());}?> The options array This array is completely optional but really usefull. The following keys are available : Options available keys Option Data Type Default Value Description prefix string '' Prefix added before XMLRPC called method name proxy string '' Proxy used for the HTTP request (default : no proxy) debug boolean FALSE Debug mode ? encoding string '' Encoding of the request 'utf-8', 'iso-8859-1' (for now, only these two ones are officialy supported) uglyStructHack boolean TRUE ugly hack to circumvent a XMLRPCEXT bug/feature , see this PHP bug for more details. The only (reasonable) counterpart of this hack is that you can't use structs with a key beginning with the string 'xml_rpc2_ugly_struct_hack_' as arguments of the called method. Making the XML_RPC2_Client object It's really easy to make the XML_RPC2_Client object. Use the following syntax : <?php// $XMLRPCServerURL is a string : 'http://pear.php.net/xmlrpc.php' (for example)// $options is an optional array : see previous section for more informations$client = XML_RPC2_Client::create($XMLRPCServerURL, $options);?> Don't try to call the XML_RPC2_Client constructor directly, use the call() static method. Call the XMLRPC exported method When the XML_RPC2_Client object is created, you can directly call the remote method as it was local. For example : <?php// We call the remote foo() method without any arguments$result1 = $client->foo();// We call the remote bar() method with two arguments (an integer : 123, a string : 'foo')$result2 = $client->bar(123, 'foo');// We call the remote foobar() method with complex data types (2 integer, a string, a structure)$result3 = $client->foobar(1, 2, 'foo', array('foo' => 1, 'bar' => 2));?> Be careful, XMLRPC spec allows some remote method names with some special characters like "." or "/"... which are not available as PHP method names. To deal with them, you have to fix a prefix in a the options array. For example : <?php$options = array('prefix' => 'foo.');$client = XML_RPC2_Client::create('http://...', $options);// We call the foo.bar() method because of the prefix 'foo.' fixed in $options array$result = $client->bar();?> In most cases, XML_RPC2 transforms automatically PHP native types into XMLRPC types (as described in the SPEC) for the request. In most cases too, XML_RPC2 transforms the XML server response into PHP native types too. Yet, there are two exceptions : 'dateTime.iso8601' and 'base64' which doesn't really exist in PHP. To manipulate explicitely these two types, you have to use special objects. Let's see a complete example : <?php// Classic usagerequire_once 'XML/RPC2/Client.php';// To manipulate these types, we need to include this file toorequire_once 'XML/RPC2/Value.php';// To get a 'dateTime.iso8601' object, you have first to set a string with an iso8601 encoded date :$tmp = "20060116T19:14:03";// Then, you call this static method to get your 'dateTime.iso8601' object$time = XML_RPC2_Value::createFromNative($tmp, 'datetime');// For 'base64', you call the same static method with your string to get a 'base64' object$base64 = XML_RPC2_Value::createFromNative('foobar', 'base64');// Then, you can use XML_RPC2_Client as usual :$options = array('prefix' => 'validator1.');$client = XML_RPC2_Client::create('http://phpxmlrpc.sourceforge.net/server.php', $options);$result = $client->manyTypesTest(1, true, 'foo', 3.14159, $time, $base64);// The remote validator1.manyTypesTest() method returns an array with the 6 given arguments$result_datetime = $result[4]; // a 'dateTime.iso8601' object$result_base64 = $result[5];   // a 'base64' object// To transform these objects into PHP native types, you have to use public properties of// these objects as follow :var_dump($result_datetime->scalar);      // will return string(17) "20060116T19:14:03"var_dump($result_datetime->xmlrpc_type); // will return string(8) "datetime"var_dump($result_datetime->timestamp);   // will return int(1137435243)var_dump($result_base64->scalar);        // will return string(6) "foobar"var_dump($result_base64->xmlrpc_type);   // will return string(6) "base64"?>

Server Side

Server Side – to be written to be written

Client Side with cache

Client Side with cache – Introduction about the XML_RPC2 "cached client side" usage Thanks to PHP5 and PEAR/Cache_Lite, it's really easy to do XMLRPC "cached client" requests with XML_RPC2. The usage is really straightforward. First, you include 'XML/RPC2/CachedClient.php' file (only this one). <?phprequire_once 'XML/RPC2/CachedClient.php';?> Second, you make an assocative arrays of options to tune XML_RPC2 (prefix, proxy, manual backend choice...). <?php$options = array(    'prefix' => 'package.',    'cacheOptions' => array(        'cacheDir' => '/tmp/',        'lifetime' => 3600    ));?> Third, you make a XML_RPC2_CachedClient object with the server URL and the with the options array. <?php$client = XML_RPC2_CachedClient::create('http://pear.php.net/xmlrpc.php', $options);?> Then, you send your request by calling the server method as it was a local method of the $client object. <?php$result = $client->info('XML_RPC2');?> This single line will encode a XMLRPC client request for the package.info() (prefix + method name) method with a single argument (the string 'XML_RPC2'), will send the request over HTTP to the server and will decode the response into PHP native types. With a single line ! Moreover, the result will be cached into a file for the given lifetime. So the next call will not send any HTTP request and it will be really fast. Of course, to catch server errors, you have to add a few lines around you client call like for example : <?phptry {    $result = $client->info('XML_RPC2');     print_r($result);} catch (XML_RPC2_FaultException $e) {    // The XMLRPC server returns a XMLRPC error    die('Exception #' . $e->getFaultCode() . ' : ' . $e->getFaultString());} catch (Exception $e) {      // Other errors (HTTP or networking problems...)    die('Exception : ' . $e->getMessage());}?> The options array This array is completely optional but really usefull. The following keys are available : Options available keys Option Data Type Default Value Description [...] [...] [...] See "non cached client side" for more options cacheOptions array array() See next table for a complete description "CacheOptions" entry is an associative array. Available keys are : CacheOptions available keys Option Data Type Default Value Description [...] [...] [...] See "Cache_Lite constructor" for more options defaultCacheGroup string '' Name of the default cache group cachedMethods array array() Array of method names to be cached (if cacheByDefault is false) notCachedMethods array array() Array of method names not to be cached (if cacheByDefault is true) cacheByDefault boolean TRUE if true, the cache is "on" by default ; else, only methods listed in cachedMethods will be cached Making the XML_RPC2_CachedClient object It's really easy to make the XML_RPC2_CachedClient object. Use the following syntax : <?php// $XMLRPCServerURL is a string : 'http://pear.php.net/xmlrpc.php' (for example)// $options is an optional array : see previous section for more informations$client = XML_RPC2_CachedClient::create($XMLRPCServerURL, $options);?> Don't try to call the XML_RPC2_CachedClient constructor directly, use the call() static method. Call the XMLRPC exported method See "non cached client side" documentation, there is no difference. The caching process is completly embedded and automatic. If a cache is available, result will be get from cache and no HTTP request will be sent. If there is no cache available for this particular call (method name and arguments), the classical XMLRPC communication will be used (and the result will be stored into a cache file for the next use).

Server Side with cache

Server Side with cache – to be written to be written