12.6. Sending XML-RPC Requests

Problem

You want to be an XML-RPC client and make requests of a server. XML-RPC lets PHP make function calls to web servers, even if they don’t use PHP. The retrieved data is then automatically converted to PHP variables for use in your application.

Solution

Use PHP’s built-in XML-RPC extension with some helper functions. As of PHP 4.1, PHP bundles the xmlrpc-epi extension. Unfortunately, xmlrpc-epi does not have any native C functions for taking a XML-RPC formatted string and making a request. However, the folks behind xmlrpc-epi have a series of helper functions written in PHP available for download at http://xmlrpc-epi.sourceforge.net/xmlrpc_php/index.php. The only file used here is the one named index.php, which is located in xmlrpc_php/. To install it, just copy that file to a location where PHP can find it in its include_path.

Here’s some client code that calls a function on an XML-RPC server that returns state names:

// this is the default file name from the package // kept here to avoid confusion over the file name require 'utils.php'; // server settings $host = 'betty.userland.com'; $port = 80; $uri = '/RPC2'; // request settings // pass in a number from 1-50; get the nth state in alphabetical order // 1 is Alabama, 50 is Wyoming $method = 'examples.getStateName'; $args = array(32); // data to be passed // make associative array out of these variables $request = compact('host', 'port', 'uri', 'method', 'args'); // this function makes ...

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.