1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

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 http://www.w3.org/TR/ws-arch/

In PHP, the soap extension can be used to create soap based web services. http://php.net/soap

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 [ http://www.eclipse.org/pdt ]

Listing 1: HelloServer.php


<?php

// Method

function sayHello($name){

return
"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().

$server->addFunction("sayHello");

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

$server->handle();

?>


Soap Client

Soap client allows you to communicate with server.

Listing 2: HelloClient.php


<?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);

print
$result; // Process the the result

}

catch(
SoapFault $ex) {

$ex->getMessage();

}



?>

HelloView

Create view for interacting with end-user

Listing 3: Helloview.php

<?php

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

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

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

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

print
"</form>";

?>

locate Helloview.php with your web browser




3 comments:

  1. Very helpfull for me.

    ReplyDelete
  2. Hello Musthaffa

    I'm very happy with your code. It helped me to implement a webservice using soap in a fastest manner with PHP.

    Unnikrishnan K
    unni@techwyseintl.com

    ReplyDelete
  3. It helped me too, great job ;)

    ReplyDelete

Related Posts with Thumbnails