Prior to version 5, PHP did not have any support for SOAP. The major SOAP implementations for PHP are PEAR::SOAP and NuSOAP. Both of these are implemented using PHP, so you do not need any other libraries or binaries to use PEAR::SOAP or NuSOAP. Just add PHP classes for these implementations and you are ready to go. First we will use NuSOAP for the SOAP client, then we will describe PEAR::SOAP, and finally we will discuss the PHP5 SOAP Extension. NuSOAP is provided by NuSphere and Dietrich Ayala. It is a set of PHP classes that allow developers to create and consume web services based on SOAP 1.1, WSDL 1.1 and HTTP 1.0/1.1. This project is hosted in SourceForge at http://sourceforge.net/projects/nusoap/ . You can download the latest version from the above link and copy the nusoap.php file into your web directory. Afterward you can include this PHP file in your code. I placed it in the same directory as the sample code itself. Let us start with a simple server. The server exposes a single SOAP method named add, which takes two integer parameters for input and returns an integer. <?php $server = new soap_server; $server->register('add'); function add($a, $b) { $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ''; $server->service($HTTP_RAW_POST_DATA); First we included nusoap.php, then created the soap server object and registered the function 'add'. Then we defined the function add. Let us save this server code as add.php. The client for this service is below. <?php $client = new soapclient('http://localhost/add.php'); $result = $client->call('add', array('a' => 5, 'b' => 7)); print_r($result); First we include the nusoap.php. Then we create a client using the soapclient function. The parameter of the soapclient function is the URL to the service. Then we use the call method of the soapclient object with the function name 'add' as the first parameter, and an array consists of the parameters of the function add as the second parameter. The output is then printed recursively using the print_r function. This is an example of the simplest SOAP client. NOTE: In the PHP5 SOAP extension, the function name for creating a SOAP client is also soapclient. So, if you want to use NuSOAP with PHP5, you need to rename the soapclient function of nusoap.php to something else. Otherwise you will get an error. We did not check for any error cases in the above example code. We can use the getError function of the soapclient object to get construction errors, as shown below. <?php $client = new soapclient('http://localhost/add.php'); $error = $client->getError(); print_r($result);
blog comments powered by Disqus |
|
|
|
|
|
|
|