News:

Choose a design and let our professionals help you build a successful website   - ITAcumens

Main Menu

A SOAP Server - PHP

Started by sukishan, Jul 14, 2009, 05:28 PM

Previous topic - Next topic

sukishan

A SOAP Server
Here is a simple server, written in PHP, that takes an ISBN (International Standard Book Number) as input, performs a lookup in an imaginary database, and returns the price of the corresponding book. In it, I use the soap_server class, and four methods of that class: the soap_server constructor, register, fault, and service:

<?php
// function to get price from database
function lookup($ISBN) {
    $query = "select price from books where isbn = ". $ISBN;
    if (mysql_connect("localhost", "username", "passwd"))
    else { $error = "Database connection error";
        return $error; }
     if (mysql_select_db("books"))
    else { $error = "Database not found";
        return $error; }
      if ($result = mysql_query($query))
    else { $error = "mysql_error()";
        return $error; }
    $price = mysql_result($result, 0, 0);
    return $price;
    }
// include the SOAP classes
require_once('nusoap.php');
// create the server object
$server = new soap_server;
// register the lookup service
$server->register('lookup');
// if the lookup fails, return an error
if $price == 0 {
    $error = "Price lookup error";
    }
if (isset($error)) {
    $fault =
$server->fault('soap:Server','http://mydomain.com/booklookupscript.php',$err
or);
    }
// send the result as a SOAP response over HTTP
$server->service($HTTP_RAW_POST_DATA);
?>The first method I use is the soap_server constructor, which creates the server object that will be doing all the work for me. I assign that object to $server. Next is register, which tells the server what to do (in this case, to call the lookup() function). The method's one parameter is the name of the function. There are other optional parameters that can be used to define the namespace and the SOAPAction information as specified in the SOAP specification, but those aren't necessary for this example. The general syntax of the register method is:

register(name, in, out, namespace, SOAPAction, style)The first parameter is the only mandatory one. in and out are arrays of input and output values; namespace and SOAPAction are used in accordance with the SOAP spec. Finally, style is used to indicate whether the data being sent is literal XML data (the default, and what I use in these examples) or RPC serialized application data.

So, the function is executed, and the returned value is passed to the server object. Then the service method returns a SOAP response to the client that initiated the request. The argument to the service method is $HTTP_RAW_POST_DATA.
A good beginning makes a good ending