|
Page 1 of 2 Web services allow you to share data across many platforms and hardware configurations. You create a webservice in PHP, pass the webservice URl to an asp.net program, and it easily calls the webservice methods to get the data from your server. PHP has various methods to create and use webservices. XML-RPC, SOAP and REST are a few. In this article we will find out how we can create and use a webservice using SOAP. Basic database programming knowledge using PHP is assumed.
First let us create a database and in it build a table using the following query.
CREATE TABLE `members` ( `mid` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `name` VARCHAR( 255 ) NOT NULL , `age` INT NOT NULL ) ENGINE = MYISAM ;
Populate the table with some records INSERT INTO `members` ( `mid` , `name` , `age` ) VALUES ( NULL , 'Leo', '33' ), ( NULL , 'Ralph', '22' ); 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. function getAge($name) {
mysql_connect('localhost','user','pass'); mysql_select_db('db'); $query = "SELECT age FROM members " . "WHERE name = '$name'"; $result = mysql_query($query);
$row = mysql_fetch_assoc($result); return $row['age']; }
We must include our NuSOAP library .
require('lib/nusoap.php');
Create the soap server instance $server = new soap_server();
Define the settings for our WSDL file such as the service name and the namespace $server->configureWSDL('dbserver', 'urn:ageserv');
Then we register our data fetching function. This step will make the server "aware" of the existence of the getAge method and the values that will pass to and from the method. If you have several methods, you must register each one separately. $server->register("getAge", array('name' => 'xsd:string'), array('return' => 'xsd:decimal'), 'urn:ageserv', 'urn:ageserv#getAge');
We invoke the webservice using the following 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 $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ''; $server->service($HTTP_RAW_POST_DATA);
SAVE THIS IN A FILE CALLED dbservice.php. That is our webservice.
|