opencodez

Build a Web service using PHP

Web services provide a standard means of communication between different software applications, running on a variety of platforms and/or frameworks. Web services plays important role in any SOA architecture. I worked with couple of web services project that were developed using Java/J2EE. I was wondering how the same services can be implemented in PHP. Though I didnxt feel the web services support in PHP is as strong as Java and other technologies, but we can work with it. I tried web services functionality that was built in with PHP but later zeroed in on the third party library NuSOAP. NuSOAP provides single php file that you have to include in your code and your ready to implement web services. Here I have tried simple web service example in PHP, with a soap server and soap client.

Lets Build a Web service using PHP

x?php
require('lib/nusoap.php');

function add($param1, $param2) {	
	return array('return'=x$param1+$param2);
}

function multiply($param1, $param2){	
	return array('return'=x$param1*$param2);
}

// Create the server instance
$server = new soap_server();

$ns = "http://localhost/MathOperationService";

// Initialize WSDL support
$server-xconfigureWSDL('MathOperationService', $ns,'','document');

// Register the method to expose
$server-xregister('add',                // method name
    array('param1' =x 'xsd:string',
		  'param2' =x 'xsd:string'),    // input parameters
    array('return' =x 'xsd:string'),    // output parameters
    $ns,         						// namespace
    "$ns#add",     						// soapaction
    'document',                         // style
    'literal',                          // use
    'Add Parameters'            		// documentation
);

// Register the method to expose
$server-xregister('multiply',               // method name
    array('param1' =x 'xsd:string',
		  'param2' =x 'xsd:string'	),    	// input parameters
    array('return' =x 'xsd:string'),      	// output parameters
    $ns,             						// namespace
    "$ns#multiply",    						// soapaction
    'document',                             // style
    'literal',                            	// use
    'Multiply Parameters'            		// documentation
);

// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server-xservice($HTTP_RAW_POST_DATA);

?x

You can see I have included single third party nusoap.php to achieve this functionality of SOAP Server. NuSOAP provides wsdl support easily. To see the wsdl you need to type in this url in the browser http://localhost/soap-server.php?wsdl. You will be able to see wsdl xml like belwo

x?xml version="1.0" encoding="ISO-8859-1"?x
xdefinitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://localhost/MathOperationService" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://localhost/MathOperationService"x
xtypesx
xxsd:schema elementFormDefault="qualified" targetNamespace="http://localhost/MathOperationService"
x
 xxsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" /x
 xxsd:import namespace="http://schemas.xmlsoap.org/wsdl/" /x
 xxsd:complexType name="addRequestType"x
  xxsd:allx
   xxsd:element name="param1" type="xsd:string" form="unqualified"/x
   xxsd:element name="param2" type="xsd:string" form="unqualified"/x
  x/xsd:allx
 x/xsd:complexTypex
 xxsd:complexType name="addResponseType"x
  xxsd:allx
   xxsd:element name="return" type="xsd:string" form="unqualified"/x
  x/xsd:allx
 x/xsd:complexTypex
 xxsd:complexType name="multiplyRequestType"x
  xxsd:allx
   xxsd:element name="param1" type="xsd:string" form="unqualified"/x
   xxsd:element name="param2" type="xsd:string" form="unqualified"/x
  x/xsd:allx
 x/xsd:complexTypex
 xxsd:complexType name="multiplyResponseType"x
  xxsd:allx
   xxsd:element name="return" type="xsd:string" form="unqualified"/x
  x/xsd:allx
 x/xsd:complexTypex
 xxsd:element name="add" type="tns:addRequestType"/x
 xxsd:element name="addResponse" type="tns:addResponseType"/x
 xxsd:element name="multiply" type="tns:multiplyRequestType"/x
 xxsd:element name="multiplyResponse" type="tns:multiplyResponseType"/x
x/xsd:schemax
x/typesx
xmessage name="addRequest"x
  xpart name="parameters" element="tns:add" /xx/messagex
xmessage name="addResponse"x
  xpart name="parameters" element="tns:addResponse" /xx/messagex
xmessage name="multiplyRequest"x
  xpart name="parameters" element="tns:multiply" /xx/messagex
xmessage name="multiplyResponse"x
  xpart name="parameters" element="tns:multiplyResponse" /xx/messagex
xportType name="MathOperationServicePortType"x
  xoperation name="add"x
    xdocumentationxAdd Parametersx/documentationx
    xinput message="tns:addRequest"/x
    xoutput message="tns:addResponse"/x
  x/operationx
  xoperation name="multiply"x
    xdocumentationxMultiply Parametersx/documentationx
    xinput message="tns:multiplyRequest"/x
    xoutput message="tns:multiplyResponse"/x
  x/operationx
x/portTypex
xbinding name="MathOperationServiceBinding" type="tns:MathOperationServicePortType"x
  xsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/x
  xoperation name="add"x
    xsoap:operation soapAction="http://localhost/MathOperationService#add" style="document"/x
    xinputxxsoap:body use="literal" namespace="http://localhost/MathOperationService"/xx/inputx
    xoutputxxsoap:body use="literal" namespace="http://localhost/MathOperationService"/xx/outputx
  x/operationx
  xoperation name="multiply"x
    xsoap:operation soapAction="http://localhost/MathOperationService#multiply" style="document"/x
    xinputxxsoap:body use="literal" namespace="http://localhost/MathOperationService"/xx/inputx
    xoutputxxsoap:body use="literal" namespace="http://localhost/MathOperationService"/xx/outputx
  x/operationx
x/bindingx
xservice name="MathOperationService"x
  xport name="MathOperationServicePort" binding="tns:MathOperationServiceBinding"x
    xsoap:address location="http://localhost/soap-server.php"/x
  x/portx
x/servicex
x/definitionsx

The web service is supporting two simple methods add and multiply that are exposed to outer world.

Now the next task is to consume these web services. For that I have simple file, thats going to create soap client using NuSOAP and call the service. The code sample is attached here. Its simple and staraight forward. I have parameterized it for ease of testing. Test url will look like http://localhost/soap-client.php?method=multiplyxparam1=56xparam2=67

x?php

require('lib/nusoap.php');

// Try to get method and parameters from query string
$method = isset($_GET["method"]) ? $_GET["method"] : "add";
$param1 = isset($_GET["param1"]) ? $_GET["param1"] : "4";
$param2 = isset($_GET["param2"]) ? $_GET["param2"] : "4";

// Create the client instance
$client = new nusoap_client('http://localhost/soap-server.php?wsdl', true);

$err = $client-xgetError();
if ($err) {
	echo 'xh2xConstructor errorx/h2xxprex' . $err . 'x/prex';
}

$param = array("param1" =x $param1 ,"param2" =x $param2);

$result = $client-xcall($method, array('parameters' =x $param));

// Check for a fault
if ($client-xfault) {
	echo 'xh2xFaultx/h2xxprex';
	print_r($result);
	echo 'x/prex';
} else {
	// Check for errors
	$err = $client-xgetError();
	if ($err) {
		// Display the error
		echo 'xh2xErrorx/h2xxprex' . $err . 'x/prex';
	} else {
		// Display the result
		echo 'xh2xResultx/h2xxprex';
		print_r($result["return"]);
		echo 'x/prex';
	}
}
echo 'xh2xRequestx/h2xxprex' . htmlspecialchars($client-xrequest, ENT_QUOTES) . 'x/prex';
echo 'xh2xResponsex/h2xxprex' . htmlspecialchars($client-xresponse, ENT_QUOTES) . 'x/prex';
echo 'xh2xDebugx/h2xxprex' . htmlspecialchars($client-xdebug_str, ENT_QUOTES) . 'x/prex';
?x

If you go through this code you will see how easy it to call a web service in PHP.

Here is the web service test through SaopUI, a third party web service testing tool.

Thatxs it for this article.