Porting a Java Program to PHP
XML-RPC
Once I actually managed to read the raw post data, parsing it and generating the appropriate response was easy. It’s just math and a little SimpleXML:
<?php
if (!isset($HTTP_RAW_POST_DATA)) {
echo "Please make sure the URL ends in a trailing slash";
echo "\n";
}
$request = $HTTP_RAW_POST_DATA;
$methodCall = simplexml_load_string($request);
$value = $methodCall->params->param->value->int;
echo "<methodResponse>\n";
echo " <params>\n";
echo " <param>\n";
echo " <value><double>";
echo fibonacci($value);
echo "</double></value>\n";
echo " </param>\n";
echo " </params>\n";
echo "</methodResponse>\n";
function fibonacci($generations)
{
$low = 1;
$high = 1;
for ( $counter = 1; $counter < $generations; $counter++) {
$oldhigh = $high;
$high = $high + $low;
$low = $oldhigh;
}
return $high;
}
I need to improve the error handling, and make sure the response MIME type is correct, but that’s basically it.
One downside: this program is noticeably slower than the Java version for even medium sized input. I guess PHP isn’t designed to do really vast arithmetic. If any PHP gurus see opportunities for optimization please holler.
November 13th, 2006 at 11:21 AM
Since you didn’t specify the directory with a trailing slash, the server is sending a 301 Moved Permanently to the client, handing back a URL that ends in a slash. A URL like http://www.elharo.com/fibonacci/XML-RPC doesn’t actually point to a valid location and most servers return the 301 instead of erroring out, the only other option they’re allowed by the spec.
http://www.elharo.com/fibonacci/XML-RPC/ would probably have worked fine, too.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Note: When automatically redirecting a POST request after
receiving a 301 status code, some existing HTTP/1.0 user agents
will erroneously change it into a GET request.
November 14th, 2006 at 5:54 AM
Aha! It is a client bug then. In this case the client is
I’ll have to file a bug report on this.
January 28th, 2007 at 6:43 PM
Thanks! I’ve been running into the same problem, and it’s been driving me nuts!