Important alert: (current site time 9/17/2014 11:11:10 AM EDT)
 

article

Learn XML-RPC (Web Service)

Email
Submitted on: 8/8/2005 1:14:16 PM
By: Philip Birk-Jensen  
Level: Intermediate
User Rating: By 8 Users
Compatibility: PHP 4.0
Views: 13625
author picture
 
     This article will guide your through creating an XML-RPC server and a client (step-by-step). And it will give you a little background theory as well.

This article has accompanying files
 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				

I'm truly sorry to do this, but I have to link (even though it's against the rules) to this article at my own server:
http://birk-jensen.dk/psc/xmlrpc.htm

The reason for this, is that PSC destroyes my HTML formatting, and my indenting in the code examples. (i've uploaded the article as well)
Index
1) Introduction
1.1) The boring introduction
1.2) What is XML-RPC?
1.3) Installing XML-RPC to PHP
2) The server
3) The Client
4) Theory
4.1) Request
4.2) Response
5) Conclusion
a. Sources b. Understanding this article
1. Introduction
As the headline below suggests it's a boring introduction, so be warned.
1.1 The boring introduction
This has absolutely nothing with XML-RPC to do, but hey I write it anyway and you're to curious to stop reading it now, HA.
Well this is my first article using this new layout (and in the PHP section, got a couple of articles at the VB section with an old layout). But the main thing I write this, is for you to skip the whole article - just the start of it! no no! wait comeback). At the end there is a section called b. Understanding this article, actually I used a couple of minutes writing this so I appreciate you use a couple of seconds reading it. It's just about the article layout, and what's what. No on the other hand it'll just bore you and scare you away, never mind forget what I said, just read on.
So you've decided to learn XML-RPC[1], or did the name just sound "freaky" and raised a little interest? If it did I suggest you read on, if you already know what XML-RPC is, then just skip the next chapter:
1.2 What is XML-RPC?
you'ree one of those people huh! Well I'll just run it through quickly and simple, so you can get on with the coding.
XML-RPC is a way to make web services, it packs the requests and responses in XML both the client and the server can understand.
Oh what, what now, you don't know what a web service is either?
Okay, well a web service is a function of some sort placed on the net (it could be a function to convert a string into all upper case letters, which we are going to make in the examples below). The smart thing is that, a web service can be programmed in any kind of language, and any other language can you it. Many big sites have a web service, for example Amazon has a web service that allows you to search books and information. Google has one as well!.
Another smart thing about XML-RPC (and to my knowledge all other web services), is that they can be run from a web server. Not only is this smart, because like many other things in programming you don't need to install some high-end fancy server. But you don't have to worry about firewalls and other kinds of protection (okay sometimes you run into a psychotic network administrator, who blocks everything but his own illegal Russian p*rn download, but hey what's the chance right?!).
1.3 Installing XML-RPC to PHP
If you've installed an extension before, this should be no problem at all, just install the XML-RPC extension. But if this is your first time, I guess I'll have to do my best guiding you through it:
Windows users: http://www.php.net/manual/en/install.windows.extensions.php
Unix users: http://www.php.net/manual/en/install.unix.php
OS X users: http://www.php.net/manual/en/install.macosx.php
For you guys(and gals) who compile PHP, just compile it with: --with-xmlrpc.

What? you didn't realy think I was going to explain this to you?
Anyway, in this article I'll try to guide you through how you make a web service (the server) and how you call a web service (the client).
2. The Server
For obviusly reasons we start making the server (Comon, we need the server first, so the client have something to connect to, geesh), which contains the function our client will be calling later on.
I've decided to comment the code, this way I don't have to explain it to you after you've read it. And you can by copying the code later on remember what it all does (if you catch my drift, because I lost the meaning of the last sentence my self):
xml_server.php

/*****
 * We start witht the functions we wan't to be web services.
 * Each of them must have 3 arguments:
 * 1st: This is the method name, which the client requests.
 * 2nd: This one is the arguments, which the client sends with the request.
 * 3rd: This data is specified by the server it self.
 *****/
function xmlEcho($method, $args, $appData)
{
 return 'Come again: '. $args[0];
}
// Just for the fun of it, let's make 2 function:
function xmlAllToUpper($method, $args, $appData)
{
 for ($i = 0; $i < count($args); $i++) {
 $args[$i] = strToUpper($args[$i]);
 }
 return $args;
}
/*****
 * Next up we'll assign the XML-RPC server handle to a variable.
 * I've chosen this "sneaky" name: $xmlServer * But you can think of this
 * as any other handle, for example, when you're working with a database, 
 * you have the connection handle, it's the same thing.
 *****/
$xmlServer = xmlrpc_server_create();
/*****
 * Now that's done it's time to tell the server which functions the
 * client can request. This is done with the xmlrpc_server_register_method
 * function (why can't they come up with some short names!). This function
 * requires 3 arguments:
 * 1st: The server handle, we just specified above.
 * 2nd: The function name, which the client calls.
 * 3rd: The function name, to run.
 *
 * This means that your function dosn't have to be named the same as the
 * function the client calls.
 *****/
xmlrpc_server_register_method($server, 'echo', 'xmlEcho');
xmlrpc_server_register_method($server, 'goLarge', 'xmlAllToUpper');
/*****
 * We need to get what ever request the client send us.
 * This is done with the $HTTP_RAW_POST_DATA variable. Nothing more
 * to say about that, so I'll just give you yet another dumb ass
 * comment ... That was it.
 *****/
$xmlRequest = $HTTP_RAW_POST_DATA;
/*****
 * We have all we need now, for the server to call the function, the
 * client requested.
 * To call this function, we use this (again rediculesly long) function:
 * xmlrpc_server_call_method, which as always take 3 arguments:
 * 1st: The server handle.
 * 2nd: The client request we just got above.
 * 3rd: What ever data you (as the server) want to send, this
 * will be passed into the $appData variable.
 *****/
$xmlResponse = xmlrpc_server_call_method($xmlServer, $xmlRequest, NULL);
// Prepare the header contents so it sends XML
header('Content-Type: text/xml');
echo $xmlResponse;
xmlrpc_server_destroy($xmlServer);
?>
All done with the server part. If you haven't figured out exactly how the server works yet, then let me give you a little insight. In short terms, it's just a php file, that is called by the client, through a normal URL. It then processes the contents which the client send, and return a result.
3. The Client
Well you made it so far, so why not make the client to test your server as well. Even though we made the server first, I must admit you'll probably be using the client a "wee" bit more. Of course it's fun to mess around with the server, but how often do you make anything others want to us right?
anyway, as you might notice, the client code contains a little socket[2] programming. If you've never worked with sockets before, don't be to glad running around screaming like a teenage girl at a (oh what the duce, do they hear now a days) Beatles concert, thinking you're going to learn anything here ... because you're not. I've decided not to go into depth with any of the socket commands, just assume you people already know them.
xml_client.php

/*****
 * First off we'll be making a function, to send our request to the
 * server.
 * This is where the feared socket programming makes it appearence,
 * take a notice at the default value for port, some people have
 * (for reasons only god may know).
 *****/
function sendRequest($host, $url, $request, $port = 80)
{
 // First off we open a connection to the server.
 if ( !$sock = fsockopen($host, $port, $errNo, $errString) ) {
 echo 'Error: '. $errNo . ' - '. $errString;
 return FALSE;
 }
 /*****
 * We prepare the HTTP header, in our request.
 * Notice we set the Content-Type to text/xml (just notice...).
 *****/
 $httpQuery = "POST ". $url ." HTTP/1.0\n";
 $httpQuery .= "User-Agent: xmlrpc\n";
 $httpQuery .= "Host: ". $host ."\n";
 $httpQuery .= "Content-Type: text/xml\n";
 $httpQuery .= "Content-Length: ". strlen($request) ."\n\n";
 $httpQuery .= $request ."\n";
 // Here we send the request to the server
 if ( !fwrite($sock, $httpQuery, strlen($httpQuery)) ) {
 echo 'Error while trying to send request';
 return FALSE;
 }
 // We get the response from the server
 while ( !feof($sock) ) {
 $xmlResponse .= fgets($sock);
 }
 // Closing the connection
 fclose($sock);
 // We strip the response from it's HTTP header
 $xmlResponse = substr($xmlResponse, strpos($xmlResponse, "\r\n\r\n") +4);
 /*****
 * To decode the XML into PHP, we use the (finaly a short function)
 * xmlrpc_decode function. And that should've done the trick.
 * We now have what ever the server function made in our $xmlRespnse
 * variable.
 *****/
 $xmlResponse = xmlrpc_decode($xmlResponse);
 // Returns the result.
 return $response;
}
/*****
 * The first thing we do, is encoding our request into an XML-RPC
 * string. This is done with the xmlrpc_encode_request function, which 
 * accepts 2 arguments:
 * 1st: Name of the function we wish to call from the server.
 * 2nd: The argument we want to parse into this function. If we
 * wish to parse more than 1 argument, we put them into an array.
 *****/
$xmlRequest = xmlrpc_encode_request('echo', 'All hail Philip the almighty... Obey!');
/*****
 * Now we call the sendRequest function, with our XML request. Remember
 * to change the host if you're not on a local computer or what ever you use.
 * And remember to change the path, if you've not saved the server directly in
 * the root (which I suspect you havent). If you hav it in the "articles/php"
 * subdirectory, you use "/articles/php/xml_server.php"
 *****/
$xmlResponse = sendRequest('127.0.0.1', '/xmlrpc_server.php', $xmlRequest);
// And at last, we print out the response!
var_dump($xmlResponse);
?>
Output: string(49) "Come again: All hail Philip the almighty... Obey!"
Hey, now wasn't that funny! Ya I bet it was ... Anyway let's take one last example just to try out all of our functions. This time we parse more than one argument with the request, so you get the idea:
EXAMPLE:

$xmlRequest = xmlrpc_encode_request('goLarge', array(1234, 'little', '1 small step'));
$xmlResponse = sendRequest('127.0.0.1', '/xmlrpc_server.php', $xmlRequest);
var_dump($xmlResponse);
?>
Output: array(3) { [0]=> string(4) "1234" [1]=> string(6) "LITTLE" [2]=> string(12) "1 SMALL STEP" }
Well I don't realy know how to explain this any better, so I guess all the practical stuff ends here.
4. Theory
I've chosen to place this section at the end of the article. This is because you don't actually need to know this to use XML-RPC, so if you're fine with just using it, or if you don't plan on using XML-RPC in the future just stop reading now. And let me just tell you, that I quickly go through this, if you want more detailed information try the XML-RPC Specification[3], that explains a bit more.
4.1 Request
I'll start by pasting in our own request to the server (the echo request we made in the example above), but notice it's without the HTTP header we send with:
<?xml version="1.0" encoding="iso-8859-1"?>
<methodCall>
<methodName>echo</methodName>
<params>
 <param>
 <value>
<string>All hail Philip the almighty... Obey!</string>
 </value>
 </param>
</params>
</methodCall>
If you've worked a little with XML before, you get it right away. If you haven't, then look at it just a little bit, and try to see if you can figure it out, it's not that hard you know ... ahh! yes not that hard right!. And for the rest of you, I'll run it through.
The line just tells us, that this is an XML document.
Try to think of it like a normal file tree. The next line is , which begins a node, this node ends at the last line . Next up Echo is the name of the function we where calling, and as you see it's the echo function being called. Then we have the arguments comming (here they call them parameters, don't ask me about the difference I do not know!), followed by yet another , note that any can hold as many they wan't. When we call our goLarge function the array is split up into 3 . Finaly we have our argument in the node. Our argument is in yet another node, this defining what type it is, this time our type is a string so All hail Philip the almighty... Obey! is used. The XML-RPC support 5 different types, the below table is stolen from the XML-RPC Specs:
or four-byte signed integer -12
0(false) or 1(true) 1
string hello world
double-precision signed floating point number -12.214
date/time 19980717T14:08:55
base64-encoded binary eW91IGNhbid0IHJlYWQgdGhpcyE=
As i said above, I wouldn't go through it all, but XML-RPC also supports arrays and structures, but you have to read about them in the XML-RPC Specs.
4.2 Response
Again I've stripped the HTML header from the server response:



 
 
 Come again: All hail Philip the almighty... Obey!
 
 

To be honest, I can't realy figure of anything to say here abuot this one. I mean, nothing's changed there's nothing new.
Now sometimes an error happens, you maybe suply to many arguments, or you might misspell a function so the server can't find it. When this happen the server will return a fault code. I've (besides stolen the idea of showing this fault code here from the XML-RPC Specs) chosen to give you an example on a fault code:



 
 
 
 faultString
 
 server error. method not found.
echos
 
 
 
 faultCode
 
 -32601
 
 
 
 

Again, it's not that difficult to figure out how this all works. But if you want more information about the you'll need to consult the XML-RPC Specs.
5. Conclusion
Finaly!
To be honest I don't really know what to make of all this, except that it works like a charm. If you compare the XML-RPC protocol to some of the other web service protocols you can find "out there", you'll find that the difference is small. Some are a little bit more advanced, some are more compact, others are exactly the same and some are useless.
Finding the right web service, is all about what you like to work with, my personal favorit is XML-RPC (hence this article). So my suggestion is try some of the other big web services, and find the one you're most comfortable with, and then stick with it!
a. Sources
[1] http://www.xmlrpc.com/
[2] http://dk.php.net/manual/en/function.fsockopen.php
[3] http://www.xmlrpc.com/spec
b. Understanding this article
Well the only purpose of this section, is to clearify a little something about this article. And it will just be done in no particular order:

- I've colored the codes my self, so if there are some color errors, please just leave some feedback, and I'll fix it. If yuo have any complaints about the colors I've used for the different syntax, then I don't want to hear about it, copy the code into your own favorit PHP editor.
- If you find anything offending, then again don't say a word or I'll get you, and I'll get you good :p
- Well that was about it, understanding this article. Now remember please leave some feadback (and if you want to vote away), nothing says "sweeeeet" like good feedback.
- Philip Birk-Jensen, Januar 2005

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come out every day, so no prevention program can catch 100% of them. For your own safety, please:
  1. Re-scan downloaded files using your personal virus checker before using it.
  2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com

 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

1/24/2005 3:54:34 AMPhilip Jensen

Please download the article, or read it from my website, beacuse PSC has messed up some of the HTML formatting, and text is missing.
I can't seen to figure out how to get passed this problem.
(If this comment was disrespectful, please report it.)

 
2/6/2005 1:44:17 AM

Great ..fine *****
(If this comment was disrespectful, please report it.)

 
9/11/2005 12:20:43 AMaLeX^rS

I'm gonna keep my eye on you. -.^
(If this comment was disrespectful, please report it.)

 
9/11/2005 12:29:25 AMaLeX^rS

LOL and to think I had to write my own XML Parse engine back in the day for Flash-AS::XML --> Server->PHP->XML[(MySQL)] --> Flash-AS::XML

Maybe that was when xmlrpc was experimental? Ne way, I like your UI Friendly Documentation. So regardless of what information your selling me, I'm buying it! -.^
(If this comment was disrespectful, please report it.)

 
8/6/2008 6:06:24 PMAric Holland

Awesome, about time XML-RPC was explained clearly!


(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.