Porting a Java Program to PHP

SOAP

The SOAP server is similar. We just parse a SOAP request and generate a SOAP envelope instead of an XML-RPC request and envelope:

<?php

if (!isset($HTTP_RAW_POST_DATA)) {
   fault("Please make sure the URL ends with a forward slash (/).
          For example, http://www.elharo.com/fibonacci/SOAP/
          not http://www.elharo.com/fibonacci/SOAP");
}
else {
    $request = $HTTP_RAW_POST_DATA;
    $envelope =  simplexml_load_string($request);
    $envelope->registerXPathNamespace('fib', 'http://namespaces.cafeconleche.org/xmljava/ch3/');
    $values = $envelope->xpath('//fib:calculateFibonacci');
    
    echo "<SOAP-ENV:Envelope
 xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' />
  <SOAP-ENV:Body>
    <Fibonacci_Numbers 
      xmlns='http://namespaces.cafeconleche.org/xmljava/ch3/'>\n";
    foreach ($values as $value) {
      fibonacci($value);
      break;
    }

    echo "</Fibonacci_Numbers>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>";
}

function fibonacci($generations)
{

  $low = 1;
  $high = 1;
  for ( $index = 1; $index <= $generations; $index++) {
    echo "      <fibonacci index='" . $index . "'>" . $low . "</fibonacci>\n";
    $oldhigh = $high;
    $high = $high + $low;
	$low = $oldhigh;
  }
  
}

function fault($message)
{

  echo "<SOAP-ENV:Envelope
 xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'>
  <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
      <faultcode>SOAP-ENV:Client</faultcode>
      <faultstring>" . $message .
      "</faultstring>
    </SOAP-ENV:Fault>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>";
  
}

Again, modulo a little error handling and adjustment of the MIME types, this is all we need.

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