Current Location: Home> Latest Articles> Comprehensive PHP SOAP Guide: Using SoapServer and SoapClient

Comprehensive PHP SOAP Guide: Using SoapServer and SoapClient

gitbox 2025-07-31

Overview

SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information between different systems. PHP offers SoapServer and SoapClient classes to facilitate publishing and consuming SOAP services.

Using SoapServer

Creating a SoapServer

To provide a SOAP service, you first need to create a SoapServer instance. You can customize it by extending the SoapServer class, as shown below:

class MySoapServer extends SoapServer {
   // Define service method
   public function myServiceMethod() {
      // Implement service logic
   }
}
// Create SoapServer instance
$server = new MySoapServer('service.wsdl');

In this example, the MySoapServer class extends SoapServer and implements the service method myServiceMethod. The instance is created with a WSDL file path.

Adding Service Methods

After creating the SoapServer instance, you can add service methods using the addFunction method, for example:

// Add service method
$server->addFunction('myServiceMethod');

This makes myServiceMethod available as a callable SOAP service method.

Starting the Server

Finally, call the handle method to start the SoapServer and listen for client requests:

// Start the server
$server->handle();

The handle method processes incoming SOAP requests and calls the appropriate service methods.

Using SoapClient

Creating a SoapClient

To call SOAP services on the client side, first create a SoapClient instance as shown:

// Create SoapClient instance
$client = new SoapClient('service.wsdl');

Passing the WSDL path initializes the SOAP client.

Calling Service Methods

Once the client instance is created, you can invoke SOAP service methods with parameters:

// Call service method
$response = $client->myServiceMethod($params);

This calls the myServiceMethod with parameters $params and stores the response in $response.

Handling SOAP Errors

SOAP calls might raise exceptions. Use a try-catch block to catch SoapFault exceptions and handle errors gracefully, as shown:

try {
   // Call service method
   $response = $client->myServiceMethod($params);
} catch (SoapFault $e) {
   // Handle error
   echo "SOAP Error: " . $e->getMessage();
}

This ensures smooth error handling and improves application robustness.

Conclusion

This article explained how to implement SOAP server and client functionality in PHP. SoapServer allows quick setup of SOAP services, while SoapClient enables easy consumption of those services. Combined with error handling, this provides a solid foundation for building reliable SOAP applications in PHP.