How to call XML-RPC in PHP

This is a brief tutorial for calling XML-RPC function in PHP. There are so many XML-RPC implementation in PHP but I will use XML-RPC for PHP 2.0 because it is purely written in PHP.

Let's go to the point. First of all, you have to create an XML-RPC client instance using xmlrpc_client().

$c = new xmlrpc_client('http://192.168.0.1:12345/RPC2');

And then create an XML-RPC message containing method name and its parameters using xmlrpcmsg().

$f = new xmlrpcmsg('echo');
$f->addParam(new xmlrpcval('Hello, World!'));

Now you are able to call the given method by sending the message through the client instance.

$r = &$c->send($f);

Don't forget to check the result of that call by checking faultCode().

  if(!$r->faultCode()) {
    $v = php_xmlrpc_decode($r->value());
  }
  else {
    print_r($r->faultString());
    $v = NULL;
  }

As you might notice from above example, you have to use xmlrpcval() to convert PHP variable to XML-RPC variable and in other side, php_xmlrpc_decode() is used for converting XML-RPC variable to PHP variable.

Tags: , ,

Post new comment