12.7. Receiving XML-RPC Requests

Problem

You want to create an XML-RPC server and respond to XML-RPC requests. This allows any XML-RPC-enabled client to ask your server questions and you to reply with data.

Solution

Use PHP’s XML-RPC extension. Here is a PHP version of the Userland XML-RPC demonstration application that returns an ISO 8601 string with the current date and time:

// this is the function exposed as "get_time( )"
function return_time($method, $args) {
   return date('Ymd\THis');
}
  
$server = xmlrpc_server_create( ) or die("Can't create server");
xmlrpc_server_register_method($server, 'return_time', 'get_time') 
    or die("Can't register method.");
  
$request = $GLOBALS['HTTP_RAW_POST_DATA'];
$options = array('output_type' => 'xml', 'version' => 'xmlrpc');

print xmlrpc_server_call_method($server, $request, NULL, $options)
    or die("Can't call method");
  
xmlrpc_server_destroy($server);

Discussion

Since the bundled XML-RPC extension, xmlrpc-epi, is written in C, it processes XML-RPC requests in a speedy and efficient fashion. Add --with-xmlrpc to your configure string to enable this extension during compile time. For more on XML-RPC, see Recipe 12.7.

The Solution begins with a definition of the PHP function to associate with the XML-RPC method. The name of the function is return_time( ) . This is later linked with the get_time( ) XML-RPC method:

function return_time($method, $args) {
   return date('Ymd\THis');
}

The function returns an ISO 8601-formatted string with the current date and ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.