Tuesday, July 28, 2009

Step by Step SOAP PHP Example

SOAP: Simple Object Access Protocol. "SOAP is a lightweight protocol for exchange of information in a decentralized, distributed environment. It is an XML based protocol that consists of three parts: an envelope that defines a framework for describing what is in a message and how to process it, a set of encoding rules for expressing instances of application-defined datatypes, and a convention for representing remote procedure calls and responses." (http://www.w3.org/TR/2000/NOTE-SOAP-20000508/)
SOAP is what you are here for. We will develop both a client and a server for our SOAP service. In this tutorial, we will be using the NuSOAP library. (http://dietrich.ganx4.com/nusoap/index.php)

WSDL: "WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information." (http://www.w3.org/TR/wsdl)%br%%br%As with XML, we will not be directly any WSDL documents. The wonderful NuSOAP library will generate WSDL documents for us. What you need to know about WSDL is that it is a document that describes a Web Service. It can tell a client how to interact with the Web Service and what interfaces that Web Service provides.

Client: We will define a Client as a script that uses a Web Service

Server: Conversely, a Server will be defined as a script that provides a Web Service.

Using SOAP with PHP - Create a SOAP server First

The first thing we need to do is to create the SOAP server. This is the script that will fetch the data from the database and then deliver it to the Client. One wonderful thing about the NuSOAP library is that this same Server script will also create a WSDL document for us.

The first step is to create a function that will fetch the data we want. Create this function just as you would any other. It is just straight up PHP. The one trick is to name the function something sensible, as this will be the name that is used when the Client contacts the Server.

function getStockQuote($symbol) {

mysql_connect('server','user','pass');
mysql_select_db('test');
$query = "SELECT stock_price FROM stockprices "
. "WHERE stock_symbol = '$symbol'";
$result = mysql_query($query);

$row = mysql_fetch_assoc($result);
return $row['stock_price'];
}
?>

Now, it is time to turn this function into a Web Service. Basically, all we have to do is include the NuSOAP library, instantiate the soap_server class and then register the function with the server. Let's go through it step by step, after which I will present the completed script.

The first thing necessary is to simply include the NuSOAP library.

require('nusoap.php'); //nusoap.php contains server and client classes for soap

Next, instantiate an instance of the soap_server class.

$server = new soap_server();

The next line is used to tell NuSOAP information for the WSDL document it is going to create for us. Specifically we specify the name of the server and the namespace, in that order.

$server->configureWSDL('stockserver', 'urn:stockquote');

Now, we register the function we created with the SOAP server. We pass several different parameters to the register method.

The first is the name of the function we are registering.

The next parameter specifies the input parameters to the function we are registering. Notice that it is an array. The keys of the array represent the names of the input parameters, while the value specifies the type of the input parameter. One thing that pure PHP programmers might find odd is that I had to specify what types my input and return parameters are with the designations of xsd:string and xsd:decimal. It is required that you describe your data properly. You are not dealing with a loosely typed language here.

The third parameter to the register method specifies the return type of the registered function. As shown below, it is fashioned in the same way as the last parameter, as an array.

The next two parameters specify the namespace we are operating in, and the SOAPAction. For more information on the SOAPAction see http://www.oreillynet.com/pub/wlg/2331.

$server->register("getStockQuote",
array('symbol' => 'xsd:string'),
array('return' => 'xsd:decimal'),
'urn:stockquote',
'urn:stockquote#getStockQuote');

Now, we finally finish it off with two more lines of code. The first simply checks if $HTTP_RAW_POST_DATA is initialized. If it is not, it initializes it with an empty string. The next line actually calls the service. The web request is passed to the service from the $HTTP_RAW_POST_DATA variable and all the magic behind the scenes takes place.

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)
? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);

Here is the completed server script which I have saved in a file named stockserver.php.

function getStockQuote($symbol) {

mysql_connect('server','user','pass');
mysql_select_db('test');
$query = "SELECT stock_price FROM stockprices "
. "WHERE stock_symbol = '$symbol'";
$result = mysql_query($query);

$row = mysql_fetch_assoc($result);
return $row['stock_price'];
}

require('nusoap.php');

$server = new soap_server();

$server->configureWSDL('stockserver', 'urn:stockquote');

$server->register("getStockQuote",
array('symbol' => 'xsd:string'),
array('return' => 'xsd:decimal'),
'urn:stockquote',
'urn:stockquote#getStockQuote');

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)
? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>


WSDL Document
At this point you have a fully functioning SOAP Server. Clients can connect to it and request data. If you haven't done so already, bring up the script in your browser and see what you get. You should get a page giving you a link to the WSDL document for the Server. Click on it and you should see the resulting WSDL document. Surprise, surprise, it is in XML! If you read over this document, you will see that it describes what happens for a request and as a response for your particular SOAP Service.

Note that while it is possible to create a SOAP Server without having it create the WSDL file, I recommend creating the WSDL document anyway. It is simple enough, so why not?


Using SOAP with PHP - Creating a SOAP Client
(Page 6 of 7 )

Creating a SOAP Client to access our Server with is just as simple as creating the Server was. Understand though that the Client does not necessarily need to be a PHP Client. The SOAP Server we just created can be connected to by any type of Client, whether that be Java, C#, C++, etc.

To create the SOAP Client, all we need to do are three things.

First, include the NuSOAP library. This is done just as it was for the Server.

require_once('nusoap.php');

Secondly, we need to instantiate the soapclient class. We pass in the URL of the SOAP Server we are dealing with.

$c = new soapclient('http://localhost/stockserver.php');

Last make a call to the Web Service. The one caveat is that the parameters to the Web Service must be encapsulated in an array in which the keys are the names defined for the service. You will see that I have an array key named 'symbol' because that is the name of the input parameter of my function. If you remember how we specified the input parameters when we registered the function with the server, you will see that this is very similar.

$stockprice = $c->call('getStockQuote',
array('symbol' => 'ABC'));

Now, here is the completed Client script, which I have saved in a file named stockclient.php.

require_once('nusoap.php');

$c = new soapclient('http://localhost/stockserver.php');

$stockprice = $c->call('getStockQuote',
array('symbol' => 'ABC'));

echo "The stock price for 'ABC' is $stockprice.";

?>