Need sample XML-RPC client code for PHP5

A very simple xmlrpc client, I use a cURL class, you can get it from: https://github.com/dcai/curl/blob/master/src/dcai/curl.php

class xmlrpc_client {
    private $url;
    function __construct($url, $autoload=true) {
        $this->url = $url;
        $this->connection = new curl;
        $this->methods = array();
        if ($autoload) {
            $resp = $this->call('system.listMethods', null);
            $this->methods = $resp;
        }
    }
    public function call($method, $params = null) {
        $post = xmlrpc_encode_request($method, $params);
        return xmlrpc_decode($this->connection->post($this->url, $post));
    }
}
header('Content-Type: text/plain');
$rpc = "http://10.0.0.10/api.php";
$client = new xmlrpc_client($rpc, true);
$resp = $client->call('methodname', array());
print_r($resp);

Looking for the same solution. This is a super simple class that can theoretically work with any XMLRPC server. I whipped it up in 20 minutes, so there is still a lot to be desired such as introspection, some better error handling, etc.

file: xmlrpcclient.class.php

<?php

/**
 * XMLRPC Client
 *
 * Provides flexible API to interactive with XMLRPC service. This does _not_
 * restrict the developer in which calls it can send to the server. It also
 * provides no introspection (as of yet).
 *
 * Example Usage:
 *
 * include("xmlrpcclient.class.php");
 * $client = new XMLRPCClient("http://my.server.com/XMLRPC");
 * print var_export($client->myRpcMethod(0));
 * $client->close();
 *
 * Prints:
 * >>> array (
 * >>>   'message' => 'RPC method myRpcMethod invoked.',
 * >>>   'success' => true,
 * >>> )
 */

class XMLRPCClient
{
    public function __construct($uri)
    {
        $this->uri = $uri;
        $this->curl_hdl = null;
    }

    public function __destruct()
    {
        $this->close();
    }

    public function close()
    {
        if ($this->curl_hdl !== null)
        {
            curl_close($this->curl_hdl);
        }
        $this->curl_hdl = null;
    }

    public function setUri($uri)
    {
        $this->uri = $uri;
        $this->close();
    }

    public function __call($method, $params)
    {
        $xml = xmlrpc_encode_request($method, $params);

        if ($this->curl_hdl === null)
        {
            // Create cURL resource
            $this->curl_hdl = curl_init();

            // Configure options
            curl_setopt($this->curl_hdl, CURLOPT_URL, $this->uri);
            curl_setopt($this->curl_hdl, CURLOPT_HEADER, 0); 
            curl_setopt($this->curl_hdl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($this->curl_hdl, CURLOPT_POST, true);
        }

        curl_setopt($this->curl_hdl, CURLOPT_POSTFIELDS, $xml);

        // Invoke RPC command
        $response = curl_exec($this->curl_hdl);

        $result = xmlrpc_decode_request($response, $method);

        return $result;
    }
}

?>

Tags:

Php

Xml Rpc