Developing SOAP Clients using PHP

SOAP (Simple Object Access Protocol) provides a flexible communication layer between applications, regardless of platform and location. As long as both the server and the client speak SOAP, they can communicate. A PHP-based web application can ask a Java database application to get some information. In this article we will try to focus on different methods of developing SOAP web service clients in PHP.

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
require_once(‘nusoap.php’);

$server = new soap_server;

$server->register(‘add’);

function add($a, $b) {
    return $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
require_once(‘nusoap.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
require_once(‘nusoap.php’);

$client = new soapclient(‘http://localhost/add.php’);

$error = $client->getError();
if($error){
     echo "Error occurred during construction!";
}
else{
     $result = $client->call(‘add’, array(‘a’ => 5, ‘b’ => 7));

     print_r($result);
}
?>

{mospagebreak title=Debugging NuSOAP}

NuSOAP has some debugging features also. They are:

  1. $client->request: This is used to get the SOAP request message.
  2. $client->response: This is used to get the SOAP response message.
  3. $client->debug_str: This is used to get the debug information.
  4. $client->fault: This is used to get faults during a remote method call.

We can use all of these to check and display all errors. Here is a complete example.

<?php
require_once(‘nusoap.php’);

$client = new soapclient(‘http://localhost/add.php’);

$err = $client->getError();
if ($err) {
    echo ‘<p><b>Constructor error: ‘ . $err . ‘</b></p>’;
}
else{
     $result = $client->call(‘add’, array(‘a’ => 5, ‘b’ => 7));
     if ($client->fault) {
    
     echo ‘<p><b>Fault: ‘;
    
     print_r($result);
          echo ‘</b></p>’;
          echo ‘<p><b>Request: <br>’;
          echo htmlspecialchars($client->request, ENT_QUOTES) . ‘</b></p>’;
          echo ‘<p><b>Response: <br>’;
          echo htmlspecialchars($client->response, ENT_QUOTES) . ‘</b></p>’;
          echo ‘<p><b>Debug: <br>’;
          echo htmlspecialchars($client->debug_str, ENT_QUOTES) . ‘</b></p>’;
     } else {
    
     $err = $client->getError();
    
     if ($err) {
         
     echo ‘<p><b>Error: ‘ . $err . ‘</b></p>’;
         
     echo ‘<p><b>Request: <br>’;
         
     echo htmlspecialchars($client->request, ENT_QUOTES) . ‘</b></p>’;
         
     echo ‘<p><b>Response: <br>’;
               echo htmlspecialchars($client->response, ENT_QUOTES) . ‘</b></p>’;
         
     echo ‘<p><b>Debug: <br>’;
          
    echo htmlspecialchars($client->debug_str, ENT_QUOTES) . ‘</b></p>’;
    
     } else {
         
     print_r($result);
    
     }
     }
}
?>

Here we are creating a soapclient object to access the add web service. If there is any error during construction, we are printing this error. If there is no error, we are calling this remote method. If this method returns any fault then we are printing the result of this function along with the request and response SOAP messages, debug string as well. If there is no fault then we are trying to get the errors that occurred during the last method call. If there are any errors then we are printing these errors along with the SOAP request, response and debug string. If there is no error then we are printing the server response. Here is a demo SOAP request message.

POST /add.php HTTP/1.0
Host: localhost
User-Agent: NuSOAP/0.6.8 (1.81)
Content-Type: text/xml; charset=ISO-8859-1
SOAPAction: ""
Content-Length: 560

<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope
  
SOAP-ENV:encodingStyle=
      "http://schemas.xmlsoap.org/soap/encoding/"
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
   xmlns:si="http://soapinterop.org/xsd">
  <SOAP-ENV:Body>
    
<ns1:add xmlns:ns1="http://testuri.org">
      
<a xsi:type="xsd:integer">5</a>
      
<b xsi:type="xsd:integer">7</b>
    
</ns1:add>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Here is a demo SOAP response message.

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Wed, 25 Jul 2007 21:32:34 GMT
X-Powered-By: ASP.NET
X-Powered-By: PHP/4.3.4
Server: NuSOAP Server v0.6.8
X-SOAP-Server: NuSOAP/0.6.8 (1.81)
Content-Type: text/xml; charset=ISO-8859-1
Content-Length: 546

<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope
  
SOAP-ENV:encodingStyle=
      "http://schemas.xmlsoap.org/soap/encoding/"
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
   xmlns:si="http://soapinterop.org/xsd">
  
<SOAP-ENV:Body>
    
<ns1:addResponse xmlns:ns1="http://tempuri.org">
      
<return xsi:type="xsd:integer">12</return>
    
</addResponse>
  
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Using NuSOAP is very simple for developing PHP web clients as described in previous code examples. Now we will try to learn about PEAR::SOAP.

{mospagebreak title=PEAR::SOAP}

Let us assume that our web service is described at http://localhost/add.wsdl. To create a PEAR::SOAP client you can use the example below.

<?php
require_once ‘SOAP/Client.php’;

$url = ‘http://localhost/add.wsdl’;
$WSDL = new SOAP_WSDL($url);
$client = $WSDL->getProxy();

$params = array(
    ’a’ => 1,
    ’b’ => 6
);

$result = $client->add($params);

print_r($result);
?>

The first line includes PEAR::SOAP’s client classes. If you have trouble loading the files, make sure your include_path contains the folder where PEAR files are stored. You first instantiate a new SOAP_WSDL object by passing $url, the location of our web service’s WSDL file, to the constructor. Next, SOAP_WSDL::getProxy() is called, and it returns a client object, $client. This is what you use to make SOAP requests. Now make the actual add() query. This method takes a few arguments, which are passed in as an (associative) array. Parameter names are the array’s keys, and their values are array values.

PEAR:SOAP converts your PHP data structures to a SOAP message written in XML and sends an HTTP request to the web server. PEAR::SOAP listens for the server’s response and parses the XML into a PHP object, which is then returned by our method and stored in $result. Then we print the result value.

Installing PEAR::SOAP is very easy if you have a pear manager installed in your server. Use the following shell command for installing PEAR::SOAP.

pear install SOAP

This will download, unzip, and install PEAR::SOAP. Depending on which packages you’ve yet to install, you may get a dependency error. First install the dependent packages and then install SOAP.

{mospagebreak title=PHP’s SOAP Extension}

From PHP version 5.0.4, PHP has a SOAP extension. Using this SOAP Extension supports SOAP client applications with a class called SoapClient, which offers the following main functions:

  • SoapClient->__construct() – Constructs a new SoapClient object.
  • SoapClient->__soapCall() – Calls a SOAP function.
  • SoapClient->__getFunctions() – Returns a list of SOAP functions.
  • SoapClient->__getLastRequestHeaders() – Returns the last SOAP request headers.
  • SoapClient->__getLastRequest() – Returns the last SOAP request.
  • SoapClient->__getLastResponseHeaders() – Returns the last SOAP response headers.
  • SoapClient->__getLastResponse() – Returns the last SOAP response.

The SoapClient->__construct() constructor creates SoapClient objects in WSDL or non-WSDL mode. This function also has some options like the location and uri options, where location is the URL to request and uri is the target namespace of the SOAP service.

SoapClient->__getFunctions() allows you to get a list of functions supported by the target node. This function is only valid in WSDL mode. After getting the supported functions, SoapClient->__soapCall() allows you to make an RPC function call on the target SOAP node. Our above client implementation can also be developed using the PHP SOAP extension as shown below.

<?php
//Create the SoapClient object
$client = new SoapClient("http://localhost/add.wsdl");

//Call the add function of SOAP server
echo $client->__soapCall("add", array(5, 7));

?>

If we are using WSDL then we can simply call the remote function as local function. The above example will generate same output as below.

<?php
//Create the SoapClient object
$client = new SoapClient("http://localhost/add.wsdl");

//Call the add function of SOAP server (possible only in WSDL Mode)
echo $client->add(5, 7);

?>

The PHP SOAP extension is very useful for creating SOAP headers with security credentials. Usernames and passwords can be securely encrypted and then added into SOAP headers using the SOAP extension of PHP.

In this article I tried to focus on some different implementations of SOAP using PHP. Both PEAR::SOAP and NuSOAP are easy to install and use. But I personally like PHP5′s SOAP extension, because it has more features than the other two. But if you are using a PHP version earlier than 5.0.4, you have to use these libraries.

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan