PHP XML-RPC Client Helper

I wrote a helper for XMLRPC client.
I also added the automatic base64 type setting for bytes data.
Just need to create the client instance and supply the service URL, then you can start to call the service.

To make you client methods is expose and developer friendly, you can create your own client class which extends XMLRPCClientHelper.

<?php
class TestXMLRPCClient extends XMLRPCClientHelper {

    /**
     * Add two number
     * @param <int> $A
     * @param <int> $B
     * @return <int>
     */
    public function add($A, $B) {
        $params = array($A, $B);
        return $this->sendRequest("add", $params);
    }
}
?>


Here is the simple example :

$url = "http://192.168.56.1:5678/service.rem";
$client = new TestXMLRPCClient();
$client->setURL($url);
$result=$client->add(1,4);  //test add
print "Add Result: $result <br>\n";

It also support the exception when there is any error occurs it will throw the exception.So you just need to use try and catch to handle that.

XMLRPCClientHelper.php. This file also included in my training materials on my previous post.

<?php

/**
 * This helper class help to create a simple XML-RPC client
 * @author Mohamad Fairol Zamzuri B Che Sayut <mfz_peyo@yahoo.com>
 */
class XMLRPCClientHelper {

    private $url;

    /**
     * Get URL
     */
    public function getURL() {
        return $this->url;
    }

    /**
     * Set URL
     * @param <string> $url URL
     */
    public function setURL($url) {
        $this->url = $url;
    }

    /**
     * Send RPC request
     * @param <string> $methodname method name
     * @param <array> $parameters parameters
     */
    public function sendRequest($methodname, $parameters) {
        for ($i = 0; $i < count($parameters); $i++) {
            if (mb_detect_encoding($parameters[$i]) === false) {
                xmlrpc_set_type(&$parameters[$i], "base64");
            }
        }
        $request = xmlrpc_encode_request($methodname, $parameters);
        $context = stream_context_create(array('http' => array(
                        'method' => "POST",
                        'header' => "Content-Type: text/xml",
                        'content' => $request
                        )));
        $file = file_get_contents($this->url, false, $context);
        $response = xmlrpc_decode($file);
        if (is_array($response) && xmlrpc_is_fault($response)) {
            throw new Exception($response['faultString'], $response['faultCode']);
        }
        return $response;
    }

}

?>

0 comments:

 
Copyright © peyotest