Wednesday, March 25, 2009

Create a web service with PHP

[W3C Definition: A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.] For more details visit

In PHP, the soap extension can be used to create soap based web services.

This article will shows you how to create a simple web service with PHP.

Soap Server

A simple server that receives a soap request and sends a response.The server takes a name from the client and returns a hello message.

Recommended IDE : Eclipse PDT [ ]

Listing 1: HelloServer.php


// Method

function sayHello($name){

"Hello $name";


// Create a SoapServer object using WSDL file.

// For the simplicity, our SoapServer is set to operate in non-WSDL mode. So we do not need a WSDL file

$server = new SoapServer(null, array('uri'=>'http://localhost/hello'));

// Add sayHello() function to the SoapServer using addFunction().


// To process the request, call handle() method of SoapServer.



Soap Client

Soap client allows you to communicate with server.

Listing 2: HelloClient.php


try {

// Create a soap client using SoapClient class

// Set the first parameter as null, because we are operating in non-WSDL mode.

// Pass array containing url and uri of the soap server as second parameter.

$client = new SoapClient(null, array(

'location' => "http://localhost/hello/HelloServer.php",

'uri' => "http://localhost/hello"));

// Read request parameter

$param = $_GET['name'];

// Invoke sayHello() method of the soap server (HelloServer)

$result = $client->sayHello($param);

$result; // Process the the result


SoapFault $ex) {





Create view for interacting with end-user

Listing 3: Helloview.php


print "<h3>Welcome to PHP Web Service</h3>";

"<form action='HelloClient.php' method='GET'/>";

"<input name='name' /><br/>";

"<input type='Submit' name='submit' value='GO'/>";



locate Helloview.php with your web browser

1 comment:


Related Posts with Thumbnails