Click here to Skip to main content
15,881,709 members
Articles / Database Development / MySQL

Developing SOAP Web Services with PHP/C#

Rate me:
Please Sign up or sign in to vote.
4.75/5 (13 votes)
28 May 2010CPOL7 min read 120.9K   10.9K   48   9
Discussion about developing PHP/SOAP Web Services and implementing them using C#.

Introduction

The goals of this research were:

  1. Learn what a Web Service is.
  2. Learn what SOAP is.
  3. Learn how to consume PHP/SOAP Web Services from a PHP website and from a Windows desktop application.

1.0 What is a Web Service?

A Web Service is defined by the W3C as "a software system designed to support interoperable machine-to-machine interaction over a network". Web services are frequently just Internet Application Programming Interfaces (APIs) that can be accessed over a network, such as the Internet.

A Web Service is simply a standard means of communication between two machines over a local or wide-area network (such as the Internet), regardless of host platform or software language. A Web Service is a set of APIs that provide data to a client application in a standard way. This data can be transferred over the network using a combination of (typically) HTTP, a supporting hypertext processor (such as PHP), and a communications protocol such as SOAP.

2.0 What is SOAP?

SOAP is a standardized means of transferring data between two machines in a client-server configuration. SOAP is a W3C standardized (W3C, 2004) means of communicating with a Web Service across a network (local or Internet). "SOAP is an XML-based messaging protocol."

SOAP messages (envelopes) are formed in XML, itself an open W3C standard. The client must have an XML parser to interpret the document. XML is platform and programming language independent, so it can be used by a wide range of computer systems. As SOAP is just a standard and not a process, it is not limited to any particular protocol (although HTTP is commonplace).

2.1 SOAP envelopes

A SOAP envelope is an XML document that is sent between the client and the server, which contains the request/response data. The document has three main elements (w3schools, 2009):

  • Envelope
  • Contains the scheme and encoding data.

  • Header
  • Contains the ID, source, destination data.

  • Body
  • Contains the request/response data (Silver Spoon Sokpop, 2009).

One of the main goals of implementations of SOAP (like NuSOAP) is to encapsulate the process of creating SOAP envelopes to ensure compatibility and compliance with the SOAP specification.

2.2 What is WSDL and why is it important to SOAP/Web Services?

WSDL is a document written in XML. The document describes a Web Service. It specifies the location of the service and the operations (or methods) the service exposes.

WSDL (Web Service Description Language) defines the Web Service and available methods to the client. This applies to all clients no matter from what context they are consuming the application.

The WSDL document also defines the following:

  • Method arguments
  • Argument data types
  • Return value data type
  • Port and binding data

Example structure of a WSDL document:

XML
<definitions>
  <types>
definition of types
</types>
  <message>
definition of a message
</message> 
   <portType>
definition of a port
</portType>
   <binding>
definition of a binding
</binding> </definitions>

2.3 What is NuSOAP?

The most viable PHP implementation of SOAP seems to be Dietrich Ayala's SOAPx4, also known as NuSOAP (Apple Inc, 09).

NuSOAP is a collection of classes that allows for rapid development of SOAP enabled PHP Web Services. NuSOAP is not a technology in itself, in the sense that it does not require any reconfiguration on the server, but rather acts as a middle man to ease the application development process.

PHP
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the server instance
$server = new soap_server;
// Register the method to expose
$server->register('hello');
// Define the method as a PHP function
function hello($name) {
    return 'Hello, ' . $name;
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>

The above example demonstrates a NuSOAP server with one method that returns the same value that was passed to it (as a string).

Walkthrough:

  • Reference the NuSOAP implementation.
  • Create a new instance of the server object, and name it.
  • Register the method "hello" with the server object.
  • Write the corresponding method and make it do "something". (In this case, return the same string that was originally passed to it.)
  • If [when] there is post data, pass it to the server object and do something with it.

The code above is as basic as a NuSOAP example gets, but it shows clearly the steps required to start making use of SOAP without having to write (or even fully understand) the implementation yourself.

PHP
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the client instance
$client = new soapclient('http://localhost/phphack/helloworld.php');
// Call the SOAP method
$result = $client->call('hello', array('name' => 'Scott'));
// Display the result
print_r($result);
?>

The client code is similar by design. Even though this example uses only PHP, it is possible to access the server using virtually any other language.

Walkthrough:

  • Reference the NuSOAP implementation.
  • Create an instance of the SOAPClient and specify the remote path of the Web Service.
  • Call the desired method and pass an argument (called 'name').
  • The Web Service responds (if request is valid) and prints the result to the screen.

The disadvantage of using third party implementations is that debugging and error handling is more difficult, as you have no knowledge of the underlying code.

3.0 Consuming SOAP/PHP Web Services

There are many ways to consume SOAP/PHP Web Services. This section focuses only on consuming a Web Service through a Windows Forms (C#) application, although any programming language that supports XML SOAP Web Services is compatible.

3.1 Windows Forms Application

Microsoft Visual Studio has extensive support for SOAP/XML Web Services. The Microsoft .NET Framework (version 1.1 and higher) has a built-in object that can be inherited to provide access to the Web Service without the need for understanding XML or reading XML documents. Object: SoapHttpClientProtocol (Microsoft MSDN, 2010).

3.1.1 How to consume a Web Service in Visual Studio 2008

To connect to the Web Service:

  • Open Visual Studio 2008.
  • Create a new project (C# or VB.NET, the process is the same).
  • In the Solution Explorer, right click References, then click "Add Web Reference".
  • Type the address to the Web Services Descriptor Language (WSDL) document. E.g.: http://localhost/customerswebservice/index.php?wsdl.
  • Click 'Go'.
  • Visual Studio will now retrieve the WSDL document and display the available methods to you.
  • Give the reference a sensible name, such as "CustomersLookup".
  • Click "Add Reference".

To invoke the service:

  • Go to your code, i.e., the load event.
  • Create a new instance of the CustomerLookup class (generated automatically for you).
  • C#
    CustomersLookup.CustomerLookup cl = new CustomersLookup.CustomerLookup(); 
  • Invoke a method as provided by the WSDL"
  • C#
    Customer[] c = cl.GetAllCustomers();

Note: This is an example; the code you type is dependent on the methods exposed by your Web Service.

4.0 Critical analysis

The objectives of this research were to learn what PHP/SOAP is and how it can be consumed from a Windows desktop application. Two projects have been produced to support this research. (See Implementation Notes at the start of this document for the Web Service details). The applications support the research because of the following:

Web Service

  • The Web Service implements NuSOAP, which itself is an implementation of SOAP
  • NuSOAP is written in PHP, as is the code that makes use of the NuSOAP implementation

Desktop application

  • Consumes all features of the Web Service itself, and makes use of all data retrieved by making calls to the Web Service
  • Desktop application makes use of WSDL to describe classes and variables within the code

The desktop application fully implements the Web Service. However, the Web Service could be expanded to provide more methods that return simple and complex types, as well as requiring simple/complex types as arguments. The Web Service could be improved by writing more supporting documentation within the WSDL as to what each method does, what arguments it requires, and what it returns. The desktop application could be improved in the same way.

The Web Service is very relevant to developers because it provides a cross platform/browser means of communication between an application and a server.

The concept of using a Web Service to provide an application with data is one that most developers can find useful. Web Services can be used, for example, to synchronize data across all of the user's devices regardless of type (laptop, desktop, mobile, smart) or Operating System (Windows Mobile, Android, Symbian).

5.0 References / Bibliography

History

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
Questionnot returning result , this is returning bool(false) value Pin
U@00725-Jul-13 2:04
U@00725-Jul-13 2:04 
Hi jpreecedev,
I had download and modified as per my system path and when run this it returning result as bool(false)

not getting exact result. could you give me suggestion.

my code is:
//index.php

<?php

require_once("nuSOAP/lib/nusoap.php");
require_once("Classes/Connection.class.php");
require_once("Classes/Customer.class.php");

$namespace = "http://localhost:8080/myfiles/customerswebservice/index.php";
// create a new soap server
$server = new soap_server();
// configure our WSDL
$server->configureWSDL("CustomerLookup");
// set our namespace
$server->wsdl->schemaTargetNamespace = $namespace;
// tell nusoap about the complex data type
$server->wsdl->addComplexType('Customer','complexType','struct','all','',
		array(
			'id' => array('name' => 'id','type' => 'xsd:int'),
			'phonenumber' => array('name' => 'phonenumber','type' => 'xsd:string'),
			'businessname' => array('name' => 'businessname','type' => 'xsd:string')
		));
// create an array of that new data type
$server->wsdl->addComplexType('Customers','complexType','array','','SOAP-ENC:Array',
		array(),
		array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:Customer[]')),'tns:Customer');

$server->register(
                // method name:
                'GetAllCustomers', 	
                // parameter list:
                array(), 
                // return value(s):
                array('return'=>'tns:Customers'),
                // namespace:
                $namespace,
                // soapaction: (use default)
                false,
                // style: rpc or document
                'rpc',
                // use: encoded or literal
                'encoded',
                // description: documentation for the method
                'Returns an exhaustive list of all customers in the database');

function GetAllCustomers()
{
	$database = new Connection();
			
	$result = $database->runQuery("SELECT * FROM customers");
	$num = mysql_num_rows($result);
	
	if($num == 0)
	{
		return "";
	}
	else
	{
		$results = array();
		
		for($i=0;$i<$num;$i++)
		{
			$tempArray = array('id' => mysql_result($result,$i,"ID"),
		 		'phonenumber' => mysql_result($result,$i,"PHONE_NUMBER"),
		 		'businessname' => mysql_result($result,$i,"BUSINESS_NAME"),
			);
			array_push($results, $tempArray);
		}
		
		return $results;
	}
}

// Get our posted data if the service is being consumed
// otherwise leave this data blank.                
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';

// pass our posted data (or nothing) to the soap service                    
$server->service($POST_DATA);                
exit();

?>

//client.php file

<?php

/**
 * <a href="/Members/author">@author</a> 
 * <a href="/Members/CopyRight">@copyright</a> 2013
 */

require_once("nuSOAP/lib/nusoap.php");
$client = new nusoap_client("http://localhost:8080/myfiles/customerswebservice/index.php?wsdl");


$prices=$client->call('GetAllCustomers',array());

var_dump($prices);

?>

result is:

bool(false) 

could you resolve this?

thanks in advance...........

Questioncan not suport utf-8 Pin
arman bay12-Dec-12 19:40
arman bay12-Dec-12 19:40 
QuestionMore details about specific problems ? Pin
Remi BOURGAREL20-Oct-10 22:37
Remi BOURGAREL20-Oct-10 22:37 
GeneralMy vote of 5 Pin
KostyaGavinsky10-Jul-10 2:04
KostyaGavinsky10-Jul-10 2:04 
GeneralRe: My vote of 5 Pin
User 674486810-Jul-10 2:54
professionalUser 674486810-Jul-10 2:54 
GeneralCan't Download file.. Pin
hirenddave7-Jul-10 22:43
hirenddave7-Jul-10 22:43 
GeneralRe: Can't Download file.. Pin
User 67448687-Jul-10 23:11
professionalUser 67448687-Jul-10 23:11 
GeneralRe: Can't Download file.. Pin
KostyaGavinsky10-Jul-10 1:58
KostyaGavinsky10-Jul-10 1:58 
GeneralRe: Can't Download file.. Pin
User 674486810-Jul-10 2:53
professionalUser 674486810-Jul-10 2:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.