Create a SOAP Web Service in PHP Using NuSOAP


SOAP stands for Simple Object Access Protocol is an XML-based Web services access protocol. The XML used to make requests and receive responses in SOAP can become extremely complex and problematic because SOAP is intolerant of errors. So we use a free open source SOAP Toolkit for PHP named NuSOAP for creating XML and to consume web services based on SOAP easily. Although REST (Representational State Transfer) is much simpler and popular than SOAP, SOAP is more standardised and has built-in error handling facilities.The SOAP is originally developed by Microsoft. SOAP is definitely the heavyweight choice for Web service access it is Language, platform, and transport independent (REST requires the use of HTTP).

In this tutorial, we will create a client which will request the price of a product by connecting to WSDL file created by the server. The WSDL file will be created by the server on the go automatically by NuSOAP library. This tutorial is mainly divided into two part. The first part deal with the creation of SOAP Web service and the second part deals with how to consume the Web service in PHP. The basic diagram of SOAP web service we are going to implement is given below.

SOAP Webservice in PHP Before we start coding we need to download NuSOAP PHP Library from their official website. The download link is given below. 

https://sourceforge.net/projects/nusoap/

After downloading it, extract it and copy the lib folder to your project folder.

LET'S START CODING

1) Creation of SOAP Web Service In PHP

The complete code for service.php file is given below.

<?php
require 'lib/nusoap.php';
require 'data.php';

$server = new nusoap_server(); // Create a instance for nusoap server

$server->configureWSDL("Soap Demo","urn:soapdemo"); // Configure WSDL file

$server->register(
	"get_price", // name of function
	array("name"=>"xsd:string"),  // inputs
	array("return"=>"xsd:integer")   // outputs
);

$server->service(file_get_contents("php://input"));

The service.php file is used to create WSDL on the fly during program execution. The first parameter of configureWSDL is the name of service and the second parameter is its URN (Uniform Resource Name). The URN is used to identify a resource by its name.

The XSD stand for XML Schema Definition. The purpose of an XML Schema is to define the legal building blocks of an XML document like the elements and attributes that can appear in a document or data types for elements and attributes etc.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives.

WSDL (Web Services Description Language) File is used to describe web services. WSDL file is written in XML. It specifies the location of the service, and the functionality offered by a web service. A client program connecting to a Web service using SOAP API can read the WSDL file to determine what operations are available on the server.

Now we need to create a data.php file to fetch necessary price details of the product. The complete code of data.php file is given below.

<?php

function get_price($name)
{
	$products = [
		"book"=>20,
		"pen"=>10,
		"pencil"=>5
	];
	
	foreach($products as $product=>$price)
	{
		if($product==$name)
		{
			return $price;
			break;
		}
	}
}

For simplicity, I am fetching the price from an array instead of the database. When you are creating API in the real world you need to fetch data from the database. If you are new to PHP then using PDO with Prepared Statement is the best way to fetch data from the database. I made details post about PDO with Prepared Statement and you can look at it by visiting the following link.

2) Consuming SOAP Web Service In PHP

We will consume the SOAP Webservice by creating a client.php file. The PHP part is given below.

<?php
require 'lib/nusoap.php';

$client = new nusoap_client("http://localhost/test/soap/service.php?wsdl"); // Create a instance for nusoap client

    if(isset($_POST['submit']))
    {
	$name = $_POST['name'];
		
	$response = $client->call('get_price',array("name"=>$name));

	if(empty($response))
	    echo "Price of that product is not available";
	else
	    echo $response;
    }
  

The instance for NuSOAP client needs to connect to WSDL file created by the server. You can found the location of WSDL file created by service.php file by executing it on the browser. The call function needs two parameters. The first parameter is the name of the registered SOAP function by server and second parameter is the array of inputs.

The complete code for client.php file with some bootstrap is given below.

<?php
require 'lib/nusoap.php';

$client = new nusoap_client("http://localhost/test/soap/service.php?wsdl"); // Create a instance for nusoap client

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>SOAP Web Service Client Side Demo</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>SOAP Web Service Client Side Demo</h2>
  <form class="form-inline" action="" method="POST">
    <div class="form-group">
      <label for="name">Name</label>
      <input type="text" name="name" class="form-control"  placeholder="Enter Product Name" required/>
    </div>
    <button type="submit" name="submit" class="btn btn-default">Submit</button>
  </form>
  <p>&nbsp;</p>
  <h3>
  <?php
	if(isset($_POST['submit']))
	{
		$name = $_POST['name'];
		
		$response = $client->call('get_price',array("name"=>$name));

		if(empty($response))
			echo "Price of that product is not available";
		else
			echo $response;
	}
   ?>
  </h3>
</div>
</body>
</html>

 

That's it. we have successfully created a SOAP service in PHP using NuSOAP SOAP toolkit for PHP. If you have any suggestions or doubts please comment below and I try will response to every one of you as early as possible.


Web development
27th Apr 2017 12:26:48 PM
PHP
9140

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.