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.

Pages: 1 2 3

3 Responses to “Porting a Java Program to PHP”

  1. Stephen Says:

    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.

  2. Elliotte Rusty Harold Says:

    Aha! It is a client bug then. In this case the client is

    java version "1.5.0_06"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-112)
    Java HotSpot(TM) Client VM (build 1.5.0_06-64, mixed mode, sharing)

    I’ll have to file a bug report on this.

  3. aaron brethorst Says:

    Thanks! I’ve been running into the same problem, and it’s been driving me nuts!

Leave a Reply