PHP and Web Services – Part 4

In the last edition of this series on web services we saw how to consume web services using SOAP. In this edition, we are going to consume web services using XML-RPC. To use XML-RPC make sure either you enable XML-RPC in your php.ini file or you compile with the xml rpc extension (depending on the type of operating system you use).

As usual with all web service code, we need to write code for both client and server. In order to access the xml-rpc server, our client need to use an intermediate interface/utility. For this, we will use the library called xmlrpc-epi. You can download the package and use the utils.php file for your client.

Let us first code the server. Here is the php code for the server(server.php):

The first line of the server code, xmlrpc_server_create() creates a xmlrpc server. The returned value (of type resource) is stored in a variable called $xmlrpc_server. Using this server variable we register three custom functions with their function names (their external name as well as internal). For this we use the function called xmlrpc_server_register_method(server,method-known-to-client,implemented-function-in-php). The data posted by the client will be in the associative array called $HTTP_RAW_POST_DATA. This data is passed to the php function that we have implemented by using the method called xmlrpc_server_call_method(server,xml,userdata). The response of the server is finally printed which will be transported back to the client.

In the server code, we have defined three custom functions – the first one called greetings_sFunction() will output a greeting to the user, the second one called getTodaysDate_sFunction() will return todays date and the third one called reverseThisString_sFunction() will return your input string reversed.

In the client code, we include the utils file ( we discussed in one of the previous paragraph that we need an interface). Next, we use one of the functions in utils called xu_rpc_http_concise(array $var) to post the data to the server. This function takes one argument which is an associative array. The elements of this array include the name of the method accessed, the path to the server code, the host name, the transport port used and any other argument that need to be passed to the calling method.

Both the server and client is ready. Run the client code to see the response from server.

This brings to the end of the series about Web Services. As usual, please email me your comments and concerns to nbphillip at yahoo dot com.